[创建C ++ dll及其函数的参数可以在c#中作为out参数调用

问题描述 投票:0回答:1

我想在c ++中创建一个函数,该函数需要两个参数(char [],int)并修改参数(类似于c#中的out参数,然后创建一个可在c#中使用的dll。

C ++示例代码:

static void funct(char * name, int size)
{
    char[] testName="John";
    name=&testName;
    size=5;
}

C#示例代码:

  const string dllLocation = "D:\\Test.dll";
  [DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)]
  private static extern void funct(StringBuilder name, int size);

这是不正确的代码。只是给我想要的一个想法。我想使用c#通过dll访问c ++函数,并获取名称和大小(无字符)。

c# c++ dllexport
1个回答
0
投票

在C ++端使用指针,并在C#端由ref将其编组。

static void funct(char** name, int* size)
{
    char[] testName="John";
    *name=&testName;
    *size=5;
}

const string dllLocation = "D:\\Test.dll";
[DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)]
private static extern void funct(ref StringBuilder name, ref int size);

请注意char数组,它可能会导致内存泄漏或更严重的崩溃,最好先测试缓冲区的大小以及要传递给C#的数据的大小,如果有足够的空间复制它,否则通知C#,它需要更大的大小,因此由C#分配。

类似这样的东西:

static int funct(char** name, int* size, int bufferSize)
{
    if(bufferSize < 4)
        return 4;

    char[] testName="John";
    memcpy(name*, &char[0], 4);
    *size=5;
    return -1;
}


const string dllLocation = "D:\\Test.dll";
[DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)]
private static extern void funct(ref StringBuilder name, ref int size, int bufferSize);

StringBuilder sb = null;
int size = 0;

//Request size
int neededSize = funct(ref sb, ref size, 0);
//Create buffer with appropiate size
sb = new StringBuilder(neededSize);
//Call with the correct size, test result.
if(funct(ref sb, ref size, neededSize) != -1)
    throw new Exception();
© www.soinside.com 2019 - 2024. All rights reserved.