user1821130
user1821130

Reputation: 45

Convert a C char * to .Net String then to byte[]

I am having a data conversion issue that need your help.

My project is an InterOp between C and C#, all the data from C is char * type, the data itself could be binary or displayable chars, I.e. each byte is in 0x00 to 0xFF range.

I am using Data marshal::PtrToStringAnsi to convert the char* to String^ in CLI code, but I found some bytes value changed. for example C382 converted to C32C. I guess it is possibly because ANSI is only capable of converting 7-bit char, but 82 is over the range? Can anyone explain why and what is the best way?

Basically what I want to do is, I don't need any encoding conversion, I just want to convert any char * face value to a string, e.g. if char *p = "ABC" I want to String ^s="ABC" as well, if *p="C382"(represents binary value) I also want ^s="C382".

Inside my .NET code, two subclasses will take the input string that either represents binary data or real string, if it is binary it will convert "C382" to byte[]=0xC3 0x82;

When reading back the data, C382 will be fetched from database as binary data, eventually it need be converted to char* "C382".

Does anybody have similar experience how to do these in both directions? I tried many ways, they all seem to be encode ways.

Upvotes: 1

Views: 401

Answers (1)

David Heffernan
David Heffernan

Reputation: 613412

The Marshal class will do this for you.

When converting from char* to byte[] you need to pass the pointer and the buffer length to the managed code. Then you can do this:

byte[] FromNativeArray(IntPtr nativeArray, int len)
{
    byte[] retval = new byte[len];
    Marshal.Copy(nativeArray, retval, 0, len);
    return retval;
}

And in the other direction there's nothing much to do. If you have a byte[] then you can simply pass that to your DLL function that expects to receive a char*.

C++

void ReceiveBuffer(char* arr, int len);

C#

[DllImport(...)]
static extern void ReceiveBuffer(byte[] arr, int len);
....
ReceiveBuffer(arr, arr.Length);

Upvotes: 2

Related Questions