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, i.e., 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)
精彩评论