如何将char ** c ++ dll转换为c#

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

我有一个要在c#上运行的c ++ dll,并且c ++的函数的返回类型为char**,我该如何获取它并打印到屏幕上。

c ++标头

extern "C" __declspec(dllexport) char**  x_browseCan();

cpp文件

char** x_browseCan() {

    browseCan(_c, 2);


    char** char_array = new char* [1000];
    int i = 0;
    for (auto it = _c->response.object_list.begin(); it != _c->response.object_list.end(); it++) {
        string asd = *it;
        int x = asd.length();
        char_array[i] = new char[x];

        strcpy(char_array[i], asd.c_str());
        i++;
    }
    return char_array ;
}

C#文件

 [DllImport(@"C:\Users\serhan.erkovan\source\repos\kkkkk_v2\x64\Debug\kkkkk_v2.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern  IntPtr x_browseCan();

   private void Browse_Click(object sender, EventArgs e)
        { 
            var a = x_browseCan();
            for (int i = 0; i < 1000; i++)
            {
                string d = Marshal.PtrToStringAnsi(a);
            }
        }

尝试将IntPtr x_browseCan()转换为IntPtr[] x_browseCan(),将var a=x_browseCan()转换为var a=new IntPtr[1000]a=x_browseCan();,但它们不起作用。

c# c++ dll marshalling
1个回答
0
投票

尝试以下内容:

[DllImport(@"C:\Users\serhan.erkovan\source\repos\kkkkk_v2\x64\Debug\kkkkk_v2.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern  IntPtr[] x_browseCan();

这里是代码

        private void Browse_Click(object sender, EventArgs e)
        {

            IntPtr[] ptrs = x_browseCan();
            for (int i = 0; i < 1000; i++)
            {
                if (ptrs[i] != IntPtr.Zero)
                {
                    string d = Marshal.PtrToStringAnsi(ptrs[i]);
                }
                else break;
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.