Home Dashboard Directory Help
Search

Allow native memory buffer to be treated as a managed byte[] by Wuzi


Status: 

Active


4
0
Sign in
to vote
Type: Suggestion
ID: 650755
Opened: 3/10/2011 5:23:47 PM
Access Restriction: Public
0
Workaround(s)
view

Description

Frequently in my integration work, I have a native memory buffer either accessed or created by a 3rd party library. When passing it to the managed world, frequently as a byte[] to be worked on by Stream.Read() or Write(), I am forced to create a temporary arrays and do a memory copy, hence a big performance loss. I would like to be able to take a native ptr and create a byte[] out of it, so it can be passed around into the managed function.

Example:

///
/// Reads up to nBuf bytes from the stream s into the buffer at pBuf.
///
unsafe int ReadData(byte* pBuf, int nBuf, Stream s)
{
    // Create a wrapper byte[] object that points to the native pBuf memory
    // The <T> type should have the same restrictions as in fixed() operator
    byte[] buf = Array.CreateNative<byte>(pBuf, nBuf);

    // Use the wrapper as a managed array object
    return s.Read(buf, 0, nBuf);
}
Details
Sign in to post a comment.
Posted by Microsoft on 1/23/2013 at 5:20 PM
Hi Wuzi,

the problem is that this isn't possible for abitrary pointers. byte[] is a managed type and thus adheres to managed rules, especially around garbage collection. From a type safety standpoint you don't want the situation where the underlying gets freed the by the 3rd party. In addition, the memory layout of byte[] is different from an arbitray void* because managed arrays store the size (AFAIK as a prefix).

In your particular case, UnmanagedMemoryStream might provide eliminate the need as well.

Thanks,
-Immo
Posted by Microsoft on 3/10/2011 at 6:14 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)
Sign in to post a workaround.