简体   繁体   中英

C# How to P/Invoke with struct array in struct?

In C#, how to P/Invoke with struct array in struct?

C Lang defined struct is below...

struct 'OuterStruct'
  int outerId
  InnerStruct[10] innerStruct 
struct 'InnerStruct'
  int innerId
  char[32] name

And C Lang defined Function is:

int ClangFunc(OuterStruct* arg)

'ClangFunc' is set values to 'arg'.

I call 'ClangFunc' from C#...

[DllImport("makefromclang.dll", EntryPoint="ClangFunc")]
public static extern int ClangFunc(IntPtr arg);

[StructLayout(LayoutKind.Sequential)]
public struct OuterStruct
{
    public int outerId;
    [MarshalAs(UnmanagementType.ByValArray, SizeConst=10)]
    public InnerStuct[] innerStruct;
}

[StructLayout(LayoutKind.Sequential)]
public struct InnerStruct
{
    public int innerId;
    [MarshalAs(UnmanagementType.ByValTStr, SizeConst=32)]
    public string name;
}

/* caller */
OuterStruct outerStruct = new OuterStruct();
IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(outerStruct));
Marshal.StructureToPtr(outerStruct, ptr, false);
int result = ClangFunc(ptr);
OuterStruct resultStruct = (OuterStruct)Marshal.PtrToStructure(ptr, typeof(OuterStruct));

Call ClangFunc is succeeded.

Results of OuterStruct.outerId and OuterStruct.innerStruct[0].innerId are set collect values.(in above resultStruct value)

But OuterStruct.innerStruct[0].name is null , why?.

I expected ""(empty string) or any Shift_JIS string. There's no way to set null value.

Thanks all.

The problem is that the value set in char[] is Shift_JIS charset. When .NET converted char[] to string, it did not consider the character set. As a result, the string value is corrupted, and the debugger seems to have a null string value.

To solve this problem, I modified the string mapped to the structure to byte[] and convert byte[] to string.

// [MarshalAs(UnmanagementType.ByValTStr, SizeConst=32)]
// public string name;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.ByValTStr, SizeConst=32)]
public byte[] name;


string str = System.Text.Encoding.GetEncoding("Shift_JIS").GetString(name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM