C # - how to marshal an LPWSTR array?

I am trying to streamline a C ++ structure that looks like this:

typedef struct _SOME_STRUCT
{
     DWORD count;
     LPWSTR *items;
}

"items" is an LPWSTR array (the exact number is indicated by "count"). In C #, I present the structure as:

[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct SOME_STRUCT
{    
     internal uint count;
     internal IntPtr items;
}

Then in my code I do something like this (where mystruct is of type SOME_STRUCT):

if (mystruct.count > 0)
{
    for (int x = 0; x < mystruct.count; x++)
    {
        IntPtr ptr = new IntPtr(mystruct.items.ToInt64() + IntPtr.Size * x);
        string item = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(ptr));
    }
}

The counter is correct, but the string element looks distorted. I'm sure I have to do something stupid, as I used to have this work with arrays of other types ... just not LPWSTR.

+3
source share
1 answer

LPWSTR is a "wide" line, i.e. Unicode PtrToStringUni will probably work better for you.

In addition, IntPtr has an operator +that is overloaded, you should be able to doIntPtr ptr = mystruct.items + (IntPtr.Size * x)

+5
source

All Articles