Wednesday, August 22, 2007

Marshall Fixed Length TCHAR Strings between Managed and Unmanaged Code

Neil Cowburn - HOWTO: Marshal fixed-length strings

"On Monday I got an internal question about marshaling fixed-length strings between managed and native code. The scenario is you have a native struct with a member defined something like this:

typedef struct SOME_STRUCT {
    DWORD size;
    TCHAR entryName[20];
}

How can you marshal the TCHAR string in managed code? You marshal it as a UnmanagedType.ByValTStr and specify the size like this:

[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    public int Size;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
    public string EntryName;
}

...

On the other hand, if the native struct is defined like this:

typedef struct SOME_STRUCT {
    DWORD size;
    TCHAR *entryName;
}

You would marshal the TCHAR pointer as a UnmanagedType.LPTStr like this:

[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    public int Size;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string EntryName;
}" [Leached about 98% of the post, just in case and so I can find it again in the future... ]

I so needed this a few years ago. Had some unmanaged DLL's with struct's/TCHAR's that I needed to call with managed code. Caching here because I just KNOW I'll need this again sometime...

No comments: