Converting C# string to char*

G

Guest

i'm calling a C++ DLL from C#.
here's C++ interface:
char* __cdecl SendCmd(void* handle, char* cmd, char* data, char* buffer);

here's my call in C#:
[DllImport("somedll.dll", CharSet = CharSet.Auto, EntryPoint = "SendCmd")]
unsafe public static extern byte* SendCmd
(void* hReader,
[MarshalAs(UnmanagedType.LPArray)] byte[] cmd,
[MarshalAs(UnmanagedType.LPArray)] byte[] data,
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer);

and the call is:
ReaderDLL.SendCommandGetData
(rdrHandle,
Encoding.ASCII.GetBytes("antenna off"),
Encoding.ASCII.GetBytes(""),
respBuffer);

the question is: when i pass the byte array to the DLL, (DLL expects
null-terminated char array) does it see a null-terminated char array?

in other words, GetBytes changes the string to byte array. how do i make
sure the byte array is null-terminated as expected by the dll?

thanks
 
M

Mattias Sjögren

in other words, GetBytes changes the string to byte array. how do i make
sure the byte array is null-terminated as expected by the dll?

You add an explicit null character at the end of the string.

Encoding.ASCII.GetBytes("antenna off\0"),

But an easier solution would be to simpliy change the parameter type
from byte[] to string (for input params) or StringBuilder (for output
buffers).


Mattias
 
B

Ben Voigt

Mattias Sjögren said:
You add an explicit null character at the end of the string.

Encoding.ASCII.GetBytes("antenna off\0"),

Better yet, avoid strings entirely, since the DLL probably recognizes
commands based on a particular sequence of bytes rather than any stringy
parsing:

ReaderDLL.SendCommandGetData
(rdrHandle,
new byte[] { 0x61, 0x6e, 0x74, 0x65, 0x6e, 0x6e, 0x61, 0x20, 0x6f, 0x66,
0x66, 0 }, // "antenna off"
new byte[] { 0 },
respBuffer);

The unicode->ansi conversion is just an extra chance for things to get
messed up.
But an easier solution would be to simpliy change the parameter type
from byte[] to string (for input params) or StringBuilder (for output
buffers).


Mattias
 
M

Mattias Sjögren

Ben,
Better yet, avoid strings entirely,

Well, from a readability and maintainability perspective I'd have to
disagree. I don't want to hunt down an ASCII table just to change the
command to "antenna on" or something.

The unicode->ansi conversion is just an extra chance for things to get
messed up.

As long as the commands only contain characters in the ASCII set it
shouldn't cause any problems.


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