gpt4 book ai didi

c# - C# 中字符串的结构映射问题

转载 作者:行者123 更新时间:2023-11-30 17:03:16 25 4
gpt4 key购买 nike

我正在尝试将(相当陈旧的)C++ 字符串消息映射到 C# 结构中,以便在某些新软件中进行处理。我遇到的问题是,当将 C++ 字符串消息映射到 C# 结构时,我丢失了字符(大概是添加了\0)。

我需要处理的消息数据如下所示:“91000222201”

Where:  "91" is one value
"0002" is the next value
"222" is the third value
"01" is the final value

我尝试的第一个结构布局是这样的:

[StructLayout(LayoutKind.Sequential, Size = 11, CharSet = CharSet.Ansi), Serializable]
public struct HeaderPacketStruct
{
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 2)]
public string Value1;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 4)]
public string Value2;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 3)]
public string Value3;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 2)]
public string Value4;
}

它处理了字符串...但产生了以下值:

HeaderPacketStruct.Value1 = "9"
HeaderPacketStruct.Value1 = "000"
HeaderPacketStruct.Value1 = "22"
HeaderPacketStruct.Value1 = "0"

当我将每个字符串上的 SizeConst 增加 1(以容纳“\0”)时,它开始删除字符:

HeaderPacketStruct.Value1 = "91"
HeaderPacketStruct.Value1 = "0022"
HeaderPacketStruct.Value1 = "01"
HeaderPacketStruct.Value1 = ""

似乎 UnmanagedType.ByValTStr 假设字符串末尾有一个“\0”。有什么办法解决这个问题吗?

顺便说一句,我能够在下面的结构中使用 char[]。但是,这个结构更难使用,因为每个值都是一个 char[] 而不是字符串(在结构内)。必须将 char[] 重新映射为字符串以进行所有处理会变得非常痛苦。

StructLayout(LayoutKind.Sequential, Size = 11, CharSet = CharSet.Ansi), Serializable]
public struct HeaderPacketStruct
{
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 2)]
public char[] Value1;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)]
public char[] Value2;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 3)]
public char[] Value3;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 2)]
public char[] Value4;
}

最佳答案

.NET 中的编码(marshal)处理总是有问题。字符串的编码是双重错误!

我做了一些测试,ByValTStr 期望最后一个字符是 '\0' 所以它读取它并忽略它(但问题是它读取它!)。您甚至不能使用 LayoutKind.Explicit 作弊,因为它会因两个字段重叠的错误而爆炸。

你可以做什么:

[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 2)]
private char[] value1;

public string Value1
{
get { return new string(this.value1); }
set { this.value1 = value.ToCharArray(); }
}

这可以正常工作。

关于c# - C# 中字符串的结构映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18799025/

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