marshal byte[] to unsigned int* through P/Invoke

N

nicewenyan

I want to pass a managed c# byte (8 bit) array into a unmanaged c++
function:

extern "C" void AddData(unsigned int* data);

I use P/Invoke on managed side to do the marshaling as following:

[DllImport("Test.dll", EntryPoint = "AddData")]
public static extern int AddData(IntPtr data);

byte[] a = new byte[] { 44, 55, 66};

IntPtr temp = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(byte)) *
a.Length);
Marshal.Copy(a, 0, temp, a.Length);

AddData(temp);

Marshal.FreeCoTaskMem(temp);

But when I debug into unmanaged function, I couldn't get correct data,
I must miss something basic. The reason I want to test this is because
later I'll have complicated structures containing byte array as member
variable, and if this works, I can use similar IntPtr inside structure
to pass it into unmanaged side.

I appreciate any help, thanks.
 
M

Mattias Sjögren

I want to pass a managed c# byte (8 bit) array into a unmanaged c++
function:

extern "C" void AddData(unsigned int* data);

Which calling convention do you use?

[DllImport("Test.dll", EntryPoint = "AddData")]
public static extern int AddData(IntPtr data);

I'd declare it as

public static extern int AddData(byte[] data);

and pass in the array direcly.

byte[] a = new byte[] { 44, 55, 66};

Passing a 3-byte array to a function expecting a 4-byte int seems like
a bad idea.

But when I debug into unmanaged function, I couldn't get correct data,
I must miss something basic.

What do you get?


Mattias
 

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