这是C++代码
DLL_API int Onvif_Discovery(char** deviceaddress, int* nDevices);
这是C#调用
[DllImport("OnvifDll.dll",EntryPoint="Onvif_Discovery",
CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)]
public extern static int Onvif_Discovery(out IntPtr deviceAddr, ref int nDevices);
其中deviceAddr的参数我试过ref string,string,stringbulider,都报错,尝试读写受保护的内存。
初学C#的妹子一枚,希望哪位有经验的C#大神给予解答!万分感激!!!
用fixed创建固定缓冲区,传入指针,参考
https://msdn.microsoft.com/zh-cn/library/f58wzh21.aspx
[DllImport("OnvifDll.dll",CharSet=CharSet.Ansi)]
public extern static int Onvif_Discovery(ref IntPtr deviceAddr, ref int nDevices);
private void button1_Click(object sender, EventArgs e)
{
int size=Marshal.SizeOf(typeof(char));
IntPtr ptr = Marshal.AllocHGlobal(size);
int num = 0;
try
{
Onvif_Discovery(ref ptr, ref num);
string str = Marshal.PtrToStringAnsi(ptr);
MessageBox.Show(str);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
我这样写的总是报错,尝试读取或写入受保护的内存。请各位帮忙看看哪里出问题了
楼主,你有解决这个问题吗