Reading from an unmanaged stream - unsafe code, IntPtr
The fol开发者_开发百科lowing 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)
Based on this pinvoke article you should be able to change the method-signature to:
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.
精彩评论