C# - 如何封送 LPWSTR 数组?
我正在尝试编组一个如下所示的 C++ 结构:
typedef struct _SOME_STRUCT
{
DWORD count;
LPWSTR *items;
}
“items”是 LPWSTR 的数组(确切的数字由“count”表示)。在 C# 中,我将结构表示为:
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct SOME_STRUCT
{
internal uint count;
internal IntPtr items;
}
然后在我的代码中,我正在执行类似的操作(其中 mystruct 的类型为 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));
}
}
计数是正确的,但字符串项出现乱码。我确信我一定做了一些愚蠢的事情,因为我之前已经对其他类型的数组进行过这项工作......只是不是 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LPWSTR 是一个“宽”字符串,即 Unicode。 PtrToStringUni 可能会更适合您。
另外,IntPtr 确实重载了 + 运算符,您应该能够执行 IntPtr ptr = mystruct.items + (IntPtr.Size * x) 操作
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 doIntPtr ptr = mystruct.items + (IntPtr.Size * x)