IntPtr 不包含本机值

本文关键字:包含本 IntPtr | 更新日期: 2023-09-27 18:31:18

>我有一个本机方法,它必须将字节数组传递给.NET包装器。natove 方法如下所示:

__declspec(dllexport) int WaitForData(unsigned char* pBuffer)
{
    return GetData(pBuffer);
}

GetData 使用 malloc 分配一个内存区域,并将一些数据(字节流)复制到其中。此字节流是通过套接字连接接收的。返回值是 pBuffer 的长度。

必须从 .NET 调用此方法。导入声明如下所示:

[DllImport("CommunicationProxy.dll")]
public static extern int WaitForData(IntPtr buffer);

[编辑]

dasblinkenlight 建议的 P/Invoke Interop Assistant 将原型转换为以下导入签名:

public static extern  int WaitForData(System.IntPtr pBuffer)

结果是一样的:调用方法后 ptr 为 0。

[/编辑]

调用

该方法后,提取结果:

IntPtr ptr = new IntPtr();
int length = Wrapper.WaitForData(ref ptr);
byte[] buffer = new byte[length];
for(int i = 0;i<length;i++)
{
    buffer[i] = System.Runtime.InteropServices.Marshal.ReadByte(ptr, i);
}
Wrapper.FreeMemory(ptr);

问题是,托管变量 ptr 不包含本机变量 pBuffer 包含的值。 当Wrapper.WaitForData返回时,ptr始终为 0,尽管pBuffer指向分配的内存区域。

原型有错误吗?指向字节数组的指针需要如何封送?

IntPtr 不包含本机值

你需要像这样传递对指针或"双指针"的引用

__declspec(dllexport) int WaitForData(unsigned char** pBuffer)

然后更改指针的值(因为它是按传递的)

*pBuffer = 'something'

其他选项 - 返回指针(然后你必须以其他方式处理 int/length)

顺便说一句,这就是为什么您自动生成的原型看起来像这样(没有 out,ref 修饰符)