how to pass binary data from C# stream to fcn in Managed C++

G

Guest

I have a byte[] of binary data received from a NetworkStream (C# code) that I need to pass to the IWMWriter object in a DLL written in Managed extensions for C++ (since the Windows Media SDK is not usable in C#) whose WriteSample function takes a byte* parameter

Do I need to marshal data? I thought I did, so I ran into alot of issues with converting the byte[] to a string and then, in the MC++ DLL, marshalling that to an IntPtr via StringToHGlobalAnsi, then casting its ToPointer() to a char*, and finally doing a memcpy of the data from char* to the byte* buffer. I guess I was trying to go from a byte[] to a byte*

If someone can point me in the right direction please, or even be so kind as to explain what I need to do? I've been spending so much time researching these newsgroups but I'm just learning bits and pieces here and there. Thanks in advance!!!
 
T

Tomas Restrepo \(MVP\)

I have a byte[] of binary data received from a NetworkStream (C# code)
that I need to pass to the IWMWriter object in a DLL written in Managed
extensions for C++ (since the Windows Media SDK is not usable in C#) whose
WriteSample function takes a byte* parameter.
Do I need to marshal data? I thought I did, so I ran into alot of issues
with converting the byte[] to a string and then, in the MC++ DLL,
marshalling that to an IntPtr via StringToHGlobalAnsi, then casting its
ToPointer() to a char*, and finally doing a memcpy of the data from char* to
the byte* buffer. I guess I was trying to go from a byte[] to a byte*.
If someone can point me in the right direction please, or even be so kind
as to explain what I need to do? I've been spending so much time
researching these newsgroups but I'm just learning bits and pieces here and
there. Thanks in advance!!!


Pin the array. That would be the easies't way around it:

Byte buffer __gc[] = yourBufferFromC#Code;
Byte __pin* umBuffer = &buffer[0];

// now pass umBuffer to your unmananged function.

Now, you shouldn't normally do this if you expect the function you're
calling to keep the array for later use or anything, because as soon as the
__pin pointer goes out of scope, the memory will be released, and the next
GC cycle might just move the memory around, causing eventually an access
violation.

If this is your case, then I suggest using Marshal::Copy() to create a copy
of the array into an unmanaged memory buffer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top