我的项目中实际遇到的是char**的二级指针,C#怎么调用呢?首先,在C++中char*和c#中的string类型是等价的。char**二级指针,就是个二位数组,等价于C#string类型的一维数组。经过一番思考,我用IntPtr接收C++的char**。问题是,用IntPtr接收char**怎么从内存中获取string数组呢?看了Marshal这个类中,有个PtrToStructure这个方法,我就从这个方向入手了。
假设C++DLL中封装了一个函数:
const char** MGetAudioDevice()
{
const char **AudioDevices =new const char*[2];
for (int i = 0; i<2; i++) {
AudioDevices[i] = new char[128];
}
AudioDevices[0] = "hello";
AudioDevices[0] = "world";
return AudioDevices;
}
C#中调用DLL
[DllImport("./Voip/VoipDLL/LIBTODLL.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr MGetAudioDevice();
封送一个结构体用于接收char**。
public struct Node
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public string[] vs;
}
private void btn_login_Click(object sender, EventArgs e)
{
IntPtr ssss = VoIP.MGetAudioDevice();
Node node = (Node)Marshal.PtrToStructure(ssss,typeof(Node));
Console.WriteLine(node.vs[0] + node.vs[1]);
//最后释放掉
Marshal.FreeHGlobal(ssss);
}
最终输出结果就是“hello world”。至此,大功告成。