从非托管流中读取 - 不安全的代码,IntPtr

时间:2009-10-21 12:35:23

标签: c# unmanaged unsafe

以下内容在Firefox(Gecko)3.5代码中公开:

[Guid("fa9c7f6c-61b3-11d4-9877-00c04fa0cf4a"), ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface nsIInputStream
{
    void Close();
    int Available();
    int Read(IntPtr aBuf, uint aCount);
    int ReadSegments(IntPtr aWriter, IntPtr aClosure, uint aCount);
    bool IsNonBlocking();
}

所以我在我的小.Net / C#应用程序中,想要使用我从代码中的其他地方返回的这个实例,但是我无法弄清楚如何处理{{1方法。

我想用int Read(IntPtr aBuf, uint aCount)方法填充我收到的内容byte[]数组,但我不知道如何处理IntPtr或如何将其转换回托管字节阵列。

任何提示/猜测/指针? (双关语无意)

2 个答案:

答案 0 :(得分:1)

基于this pinvoke article,您应该能够将方法签名更改为:

int Read([Out] byte[] aBuf, uint aCount);

答案 1 :(得分:0)

使用现有定义,您需要使用Marshal.AllocHGlobal来分配非托管内存块并将指针传递给该方法。返回时,使用Marshal.Copy将内存复制到托管字节[],并使用Marshal.FreeHGlobal释放分配的非托管内存。