Marshalling a char* inside a struct with null characters :(

S

Steve

Typical story, I want to call an unmanaged c DLL from a c# app. I have most
of the methods working, there is one that is stubborn.

<c code>

union DEVICE_T
{
/// this buffer holds the complete device information
/// and is overlayed by the following information structure
CHAR buffer[80];
struct
{
WORD endian;
WORD id;
BYTE string[32];
WORD mainStart;
WORD infoStart;
WORD ramEnd;
WORD nBreakpoints;
WORD emulation;
WORD clockControl;
WORD lcdStart;
WORD lcdEnd;
WORD vccMinOp;
WORD vccMaxOp;
WORD hasTestVpp;
WORD ramStart;
WORD ram2Start;
WORD ram2End;
WORD infoEnd;
ULONG mainEnd;
};
};


Here is the function signature that I'm trying to call:
MSP430_Identify(CHAR* buffer, LONG count, LONG setId);

</c code>


And here is my C# code:

<C# code>

[DllImport(m_dllName)]
public static extern int MSP430_Identify(
[MarshalAs(UnmanagedType.LPStr)]StringBuilder buffer, int count, int setId);


Here is the code where I call it:
StringBuilder identityBuffer = new StringBuilder(80, 80);
TIMSP430Driver.MSP430_Identify( identityBuffer, 80, 0);

</C# code>


The StringBuilder approach is the only one I have been able to get any sort
of result from. ost combinations of ref, out, char[] and string cause
exceptions, but the StringBuilder method gives me 3 characters and they are
valid. The catch is, since this isn't a valid string but rather a byte
buffer, there are some 0 character in the string and that is stopping the
StringBuilder from getting the entire results. I need to tell it to get all
bytes, not just until it hit a terminator.

An example of the correct result is:
[0] 85 'U' char
[1] -86 'ª' char
[2] 5 '?' char
[3] 0 char
[4] 77 'M' char
[5] 83 'S' char
[6] 80 'P' char
[7] 52 '4' char
[8] 51 '3' char
[9] 48 '0' char
[10] 70 'F' char
[11] 49 '1' char
[12] 52 '4' char
[13] 55 '7' char
[14] 0 char
... etc


What do I need to do to get the StringBuilder to cooperate with me? Any
suggestions welcome.
Thanks!
Steve
 

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