Interop with Array for Char

C

ckkwan

Dear All,

I have a C++ structure which is passed in and returned from a DLL.

struct S
{
char A[16];
char B[8];
}

Question:

How can I represents this in a CSharp structure?

Byte Array in CSharp is a reference, I can't have them in the
structure :(
 
J

Jeroen Mostert

Dear All,

I have a C++ structure which is passed in and returned from a DLL.

struct S
{
char A[16];
char B[8];
}

Question:

How can I represents this in a CSharp structure?

Byte Array in CSharp is a reference, I can't have them in the
structure :(

Assuming the "char" arrays represent strings (and not byte arrays):

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct S {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string A;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string B;
}

If they do represent byte arrays (in which case the C++ author was probably
sloppy, because he ought to have used "unsigned char"):

[StructLayout(LayoutKind.Sequential)]
struct S {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] A;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] B;
}

Look up the topic "Default Marshaling for Arrays" in the MSDN for enlightenment.
 
C

ckkwan

Thanks J for the answer.

In fact this is a structure to store some personal data, and it is in
UNICODE form. So, it is actually TCHAR.

I am aware that the conversion from char in C# to TCHAR in VC++ is not
that straight forward (C# supports sorrogate paris). That is why I
simplify it to char[] for the time been.

C++ never insist us to use unsigned char for any binary array. We can
even use int[] or long[] or short[] (but need to set #pragma
pack(1)) :)
 

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