Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshaling a c char array[128] to c#

Simple question, but I can't find a straight answer: I want to have a char array of 128 bytes in my C structure. I am running this under 64bit Windows. I want to marshal this over to c#, using the following:

The C code:

typedef struct s_parameterStuct
{
    int count;
    char name[ 128 ];
} parameterStruct;

And the c# code:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class parameterStuct
{
    public int count;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
    public char[] name;
}

Since a char is 2 bytes in c#, should the SizeConst be 128 or 256. Both seem to work fine, but I know only one of them is correct.

like image 619
PaeneInsula Avatar asked Aug 20 '12 20:08

PaeneInsula


1 Answers

The size would be 64, since 64 2-byte quantities have the same size as 128 1-byte ones.

I'd use a byte array for marshaling because otherwise you'll have to put up with splitting values in order to get the C chars (which are single bytes).

like image 174
Wug Avatar answered Sep 23 '22 07:09

Wug