Stewart Stoakes
Stewart Stoakes

Reputation: 857

Passing a byte array from C# into C++ com object with C++ filling array

I need to pass a byte array into a C++ com object from C#. C++ will then fill the buffer for C# to read.

c++ function definition

STDMETHODIMP CSampleGrabber::GetBuffer(byte* bd)
{
    int p=0;
    while (p< nBufSize) {
        bd[p]=pLocalBuf[p];
        p++;
    }

c# code :

byte[] byTemp = new byte[nBufSize];      
igb.GetBuffer(ref byTemp);

This crashes the program with no exception. Please can someone help. Thanks

SOLVED:

with

byte[] byTemp = new byte[nBufSize];

GCHandle h = GCHandle.Alloc(byTemp, GCHandleType.Pinned); 
igb.GetBuffer(h.AddrOfPinnedObject());

Thanks

Upvotes: 0

Views: 5171

Answers (2)

Izzy
Izzy

Reputation: 1816

I know this is an old question, but Google brought me here so it might bring someone else. If you're using P/Invoke to call:

... GetBuffer(byte* bd)

it should look something along the lines of

[DllImport("MyDll.dll")]
... GetBuffer(ref byte bd);

And a buffer array in c# should be passed in like this:

var arr = new byte[Length];
GetBuffer(ref arr[0]);

This also works with char*, as you can just pass in the same byte array reference and then use string s = Encoding.<encoding>.GetString(arr);

Upvotes: 0

arx
arx

Reputation: 16904

The parameter should not be declared as ref. You want something like:

uint GetBuffer(byte[] bd);

If you include the ref you are passing a pointer to the array, when you just want the array. (And by array, I mean pointer to the first element.)

Upvotes: 2

Related Questions