我正在用 c# 编写一个应用程序,它使用我用 pinvoke 在 c 中编写的 dll。 这是dll的代码:
__declspec(dllexport) char** foo()
{
int i;
char arr[5]="omer";
char **str_arr=(char**)malloc(sizeof(char*));
str_arr[0]=(char*)malloc(sizeof(char)*5);
strcpy(str_arr[0],arr);
return str_arr;
}
这是c#中的代码:
class Program
{
[DllImport("gg.dll", CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern char** foo();
static unsafe void Main(string[] args)
{
int [] arr;
int i;
char [] char_arr={'o','m','e','r'};
string[] string_arr=new string [1];
char** str_arr;
str_arr=foo();
for (i = 0; i < 4; i++)
{
char_arr[i]=str_arr[0][i];
}
string_arr[0] = new string(st);
free(*str_arr);
free(str_arr);
}
}
现在,当指针返回时,第一个字符数组的内容是乱码(中文字符)而不是“omer”,为什么呢?
我认为这可能是因为 c# 中的 char 数组可能使用 unicode 编码,但是当我在调用函数 foo 后更改 char_arr 中的内容值之前测试它时,它表示 ASCII 中的字母
最佳答案
您的 C
代码正在使用单字节字符,而您的 C#
代码则需要 16 位双字节字符。
看看 related question .
关于c# - pinvoke将ascii字符数组返回给c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24586727/