简体   繁体   中英

C# - how to marshal an array of LPWSTR?

I am trying to marshal a c++ struct that looks like the following:

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

"items" is an array of LPWSTR's (the exact number is indicated by "count"). In C# I am representing the struct as:

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

Then in my code I am doing 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 count is correct, but the string item is coming out garbled. I'm sure I must be doing something daft as i've had this work before with arrays of other types...just not LPWSTR.

LPWSTR is a 'wide' string, ie, Unicode. PtrToStringUni will probably work better for you.

Also, IntPtr does have the + operator overloaded, you should be able to do IntPtr ptr = mystruct.items + (IntPtr.Size * x)

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