Search code examples
c#pinvokemarshalling

C# Marshal typedef char T_STRING[MAX_STRING_SIZE]


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(...)].


Solution

  • 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;
    }