gpt4 book ai didi

.net - 什么 .NET UnmanagedType 是 Unicode (UTF-16)?

转载 作者:行者123 更新时间:2023-12-03 02:54:50 24 4
gpt4 key购买 nike

我将字节打包到一个结构中,其中一些对应于 Unicode 字符串。以下内容适用于 ASCII 字符串:

[StructLayout(LayoutKind.Sequential)]
private struct PacketBytes
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string MyString;
}

我以为我能做到

[StructLayout(LayoutKind.Sequential)]
private struct PacketBytes
{
[MarshalAs(UnmanagedType.LPWStr, SizeConst = 32)]
public string MyString;
}

使它成为Unicode,但这不起作用(字段值为空,其他字段的值不正确,表明字节解包被搞乱了)。 (由于该字段是具有其他字段的结构的一部分,为了清楚起见,我省略了这些字段,因此我不能简单地更改包含结构的 CharSet。)

知道我做错了什么吗?

这是输入(64 字节,小端):

31:00:31:00:32:00:33:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00

输出应为 Unicode 字符串“1123”。

最佳答案

我将通过声明字符串类型的嵌套结构来做到这一点。 “内部”结构可以声明其CharSet。这和我博客上的解决方案类似:http://nitoprograms.blogspot.com/2010/02/interop-multidimensional-arrays-of.html

例如:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct StringSizeConst32AsString
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
private string Value;

public static implicit operator string(StringSizeConst32AsString source)
{
return source.Value;
}

public static implicit operator StringSizeConst32AsString(string source)
{
// Note that longer strings would be silently truncated
// if we didn't explicitly check this.
if (source.Length >= 32)
throw new Exception("String too large for field: " + source);

return new StringSizeConst32AsString { Value = source };
}
}

关于.net - 什么 .NET UnmanagedType 是 Unicode (UTF-16)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2951719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com