IntPtr不包含本机值

时间:2012-04-17 10:21:17

标签: c# .net interop compact-framework pinvoke

我有一个本机方法,必须将一个字节数组传递给.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助手将原型转换为以下导入签名:

public static extern  int WaitForData(System.IntPtr pBuffer)

结果相同:调用方法后ptr为0。

[/ EDIT]

调用该方法,结果被提取出来:

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包含的值。 ptr返回时Wrapper.WaitForData始终为0,尽管pBuffer指向已分配的内存区域。

原型中有错误吗?如何编组指向字节数组的指针?

1 个答案:

答案 0 :(得分:3)

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

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

然后更改指针的值(因为它通过传递)

*pBuffer = 'something'

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

btw这就是为什么你自动生成的原型看起来像这样(没有out,ref修饰符)