C# Marshal typedef char T_STRING[MAX_STRING_SIZE]

2019-08-12 04:31发布

问题:

How to Marshal a:

[C++]
#define MAX_STRING_SIZE 255
typedef char T_STRING[MAX_STRING_SIZE];
typedef struct
{
    unsigned long m_ID;
    T_STRING m_name;
} Result;

In C#?

Currently I am doing this (but it does not work):

[C#]
[StructLayout(LayoutKind.Sequential)]
public struct Result
{
    public uint m_ID;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
    public char[] m_name;
}

I have tried to use a IntPtr instead of char[] with equal non-working result. Both with and without [MarshalAs(...)].

回答1:

Marshal it like this:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Result
{
    public uint m_ID;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
    public string m_name;
}