简体   繁体   中英

Write unmanaged byte array to memory mapped file

Is there a way to transfer unmanaged memory into a memory mapped file without needing to Marshal the unmanaged memory first?

I'm using an API which supplies me with ripped PDF data via a delegate. I get an IntPtr pointing to the data which I then use to marshal the unmanaged byte array to a managed byte array. I then write that array to a memory mapped file. I'm doing no processing on the byte array. All I do is write the array to a memory mapped file, then at a later point in time, I read the data back from the file and send it across the wire to another application (which is not a .Net application).

Is there a way I can do this without Marshaling? Is there a way that I could write the unmanaged data directly into a memory mapped file?

private void Callback( IntPtr data, int length )
{
    var buffer = new byte[ length ];
    Marshal.Copy( data, buffer, 0, length );
    _memoryMappedViewStream.Write( buffer, 0, length );
}

Ultimately, this comes down to: is there an API that lets you pass in a pointer for the PDF code to write to. If so, you can presumably get hold of the unmanaged pointer for the memory mapped file via a view-accessor ( CreateViewAccessor ) and .SafeMemoryMappedViewHandle.AcquirePointer() - hand that pointer to the other API to write to directly, without you ever having to get in the middle. Remember to call ReleasePointer() when you've finished with it.

If that doesn't exist, then you'll need to copy the data once, which is what you're doing. I might be tempted to use Unsafe.CopyBlock (from System.Runtime.CompilerServices.Unsafe ) rather than Marshal.Copy , but I expect that they're doing the same thing.

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