Marshaling a fixed-length array of C ++ char as a member of a structure

I am trying to call an unmanaged C ++ function that has a structure as an input parameter. The structure is defined in the header file as follows:

struct MyStruct
{
int     siOrder;
char     aaszNames[6][25];
int     siId[6];
int     siTones[6];        
};

I tried to declare a managed structure as follows:

[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct {

public int siOrder;

[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=150)]
public string aaszNames;

[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=6, ArraySubType=UnmanagedType.I4)]
public int[] siId;

[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=6, ArraySubType=UnmanagedType.I4)]
public int[] siTones;
}

But without any success. I assume that marshaling fails, since aaszNames is actually an array of six 25 long zero strings. I tried declaring aasz names as

 [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=150)]
 public char[] aaszNames;

filling the array with zeros where necessary. But, again, nothing.

Is there something I am missing? What am I doing wrong? What is the best way to marshal this 2-D char array?

Any clues please.

+3
4

#:

[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct_Name
{
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)]
    public string name;
}

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStruct
{
    public int siOrder;

    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6)]
    public MyStruct_Name aaszNames;

    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I4)]
    public int[] siId;

    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I4)]
    public int[] siTones;
}

C.

aaszNames! .

MyStruct foo = new MyStruct();
for (int i = 0; i < 6; i++)
{
    foo.aaszNames[i] = new MyStruct_Name();
    foo.aaszNames[i].name = "";
}

!

+5
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=150)]
 public char[] aaszNames;

. , /

0

c-, C-.
, .
C,/0 , 6 , # 5 /0.

0
char aaszNames[6][25];

char ++ - 8 ~

char # Type - Unicode (16 )!

char ++ ↔ #

-3
source

Source: https://habr.com/ru/post/1732862/


All Articles