Timur Mustafaev
Timur Mustafaev

Reputation: 4929

Convert IntPtr to byte[] c#

I receive IntPtr value from C++ library method and i need to get byte[] array from this received IntPtr. When I try do this:

byte[] myArray = new byte[Marshal.SizeOf(myReceivedIntPtr)];
Marshal.Copy(myReceivedIntPtr, myArray, 0, Marshal.SizeOf(myReceivedIntPtr));

I receive an exception: AccessViolationException. What I missed?

EDIT:

Here is Method name and params in header of C++ library:

int MSR_DecodeTrack(char *AscBuff, unsigned char *BinBuff, unsigned char bpc, unsigned char parity, unsigned char ss, unsigned char es);

And I call it from C# this way:

 UInt32 result;
 IntPtr myReceivedIntPtr;
 IntPtr BinBuff;
 byte BPC1 = 7, Parity1 = 1, SS1 = 0x05, ES1 = 0x1F;

 result = MSR_DecodeTrack(ref myReceivedIntPtr, ref BinBuff, BPC1, Parity1, SS1, ES1);

And here is else code:

 byte[] myArray = new byte[Marshal.SizeOf(myReceivedIntPtr)];
 Marshal.Copy(myReceivedIntPtr, myArray, 0, Marshal.SizeOf(myReceivedIntPtr));

Upvotes: 1

Views: 6748

Answers (2)

Ron Klein
Ron Klein

Reputation: 9450

The method named MSR_DecodeTrack should also return the length of each array it allocates.

As far as I know, when you allocate an array in C/C++ environment, you get a pointer to the zero element of that array, nothing more. For that reason, you should also somehow return the length of the allocated array back to the caller. It can be done by an additional "ref" parameter.

HTH.

Upvotes: 0

Russell Troywest
Russell Troywest

Reputation: 8776

I'm pretty sure Marshal.SizeOf(myReceivedIntPtr) will return the size of the IntPtr object, not the size of the unmanaged array. You will need to get the size of the unmanaged array from the c++ library.

I haven't had to do this in a while so I'm a bit rusty but from looking at the c++ headers I think it is expecting a pointer to a buffer. You are giving it a pointer to a pointer (intptr is a pointer and passing it by ref means you are passing the c++ code a pointer to that pointer). Firstly, don't use ref. Secondly, I suspect you are supposed to be passing it an already sized buffer - is there any documentation describing what you are supposed to pass to the function? What is the return code from the function? You are checking it for success aren't you? ;)

Upvotes: 2

Related Questions