c# - pinvoke将ascii字符数组返回给c#

标签 c# c dll pinvoke dllimport

我正在用 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/

相关文章:

c++ - 为什么我的 VBA 在 C++ DLL 中找不到函数?

mongodb - 您如何确定mongo php扩展名的正确dll?

c# - Automapper ProjectTo 将 ToList 添加到子属性中

c# - WebAPI 路由中的通配符参数不应该匹配

c++ - 使用 void 指针时转换函数(CUBA Nint 例程)

c - 需要一些关于在 C 中类型转换的澄清

java - 左倾树+符号表

c# - Html.EditorFor 用于带逗号的小数字段

c# - Linq-to-SQL ToDictionary

java - tomcat 5 java.lang.UnsatisfiedLinkError : tomcat\apache-tomcat-5. 5.36\bin\tcnative-1.dll AMD 64 位平台上的 : Can't load IA 32-bit . dll