简体   繁体   中英

Reading from an unmanaged stream - unsafe code, IntPtr

The following is exposed in the Firefox (Gecko) 3.5 code:

[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();
}

So here I am in my little .Net/C# app, wanting to make use of an instance of this that I have returned from elsewhere in my code but I'm having trouble working out what to do with the int Read(IntPtr aBuf, uint aCount) method.

I want to fill a local byte[] array with the contents I receive from the Read method, but I'm not sure what to do with IntPtr or how to translate that back into a managed byte array.

Any tips/guesses/pointers? (pun not intended)

基于这篇引人入胜的文章,您应该可以将方法签名更改为:

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

With the existing definition, you'll need to use Marshal.AllocHGlobal to allocate unmanaged chunk of memory and pass the pointer to it to the method. Upon return use Marshal.Copy to copy memory to a managed byte[] and release the allocated unmanaged memory by using Marshal.FreeHGlobal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM