.net 将字节流解析为结构/类
我有一个字节流,我需要解析成一个结构,我还需要能够将结构解析回一个字节流 下面是一个使用BitConverter解析值的示例。我希望有一个更有效的方法来做这件事,因为我的结构是巨大的.net 将字节流解析为结构/类,.net,visual-c++,.net,Visual C++,我有一个字节流,我需要解析成一个结构,我还需要能够将结构解析回一个字节流 下面是一个使用BitConverter解析值的示例。我希望有一个更有效的方法来做这件事,因为我的结构是巨大的 ref struct TestStruct { int TestInt; float TestFloat; }; int main(array<System::String ^> ^args) { // populating array - just for demo, it'
ref struct TestStruct
{
int TestInt;
float TestFloat;
};
int main(array<System::String ^> ^args)
{
// populating array - just for demo, it's really coming from a file
array<unsigned char>^ arrBytes = gcnew array<unsigned char>(8);
Array::Copy(BitConverter::GetBytes((int)1234), arrBytes, 4);
Array::Copy(BitConverter::GetBytes((float)12.34), 0, arrBytes, 4, 4);
// parsing to struct - I want help
TestStruct^ myStruct = gcnew TestStruct();
myStruct->TestInt = BitConverter::ToInt32(arrBytes, 0);
myStruct->TestFloat = BitConverter::ToSingle(arrBytes, 4);
String^ str = Console::ReadLine();
return 0;
}
ref struct TestStruct
{
智力测验;
浮动测试浮动;
};
int main(数组^args)
{
//填充数组-只是为了演示,它实际上来自一个文件
数组^arrBytes=gcnew数组(8);
数组::复制(位转换器::GetBytes((int)1234),arrBytes,4);
数组::复制(位转换器::GetBytes((float)12.34),0,arrBytes,4,4);
//解析到struct-我需要帮助
TestStruct^myStruct=gcnewteststruct();
myStruct->TestInt=BitConverter::ToInt32(arrBytes,0);
myStruct->TestFloat=BitConverter::ToSingle(arrBytes,4);
字符串^str=Console::ReadLine();
返回0;
}
是对.NET中序列化的解释
<>一般C++(未托管),请看 C++和.NET两个。对于C++,你应该能够沿着行一些事情。
char buffer[sizeof(MYSTRUCT)];
memcopy((char*) &mystruct, buffer, sizeof(MYSTRUCT));
如果要避免单独保存每个项,则不能保证这些类存储在连续的内存块中。这很烦人,但这是托管代码的“特性”之一——你必须让它为你管理它
-Adam对于这样的东西,您通常使用代码生成器。假设源代码如下所示:
struct a {
int i;
}
struct b {
string name;
struct a a;
}
您要做的是编写一个简单的解析器,在源文件(可能是某些头文件)中搜索“struct”,然后读取结构的名称(介于“struct”和“{”)之间的任何内容。将此内容写入输出:
cout << "struct " << name << " * read_struct_" << name << " (stream in) {" << NL
<< " struct " << name << " * result = malloc (sizeof(struct " << name << "));" NL
parseFields (headerStream);
cout << " return result;" << NL << "}" << NL ; }
cout << "read_" << fieldType << "(in, &result->" << fieldName << ");" << NL;
这允许您定义如何在其他地方(在实用程序模块中)读取或写入int
现在,您有了从头文件读取结构定义的代码,并创建了可以从某个流中读取结构的新代码。复制此代码以将结构写入流。编译生成的代码,就完成了
您还需要编写单元测试来验证解析是否正确:)只需在内存中创建一个结构,使用write方法将其保存在某个位置并重新读取。现在这两个结构应该是相同的。您需要编写第三个代码生成器来创建代码来比较两个结构。序列化是gre在,但在我的情况下,我不需要额外的,我必须做同样的工作来完全控制比特。我想这可能是解决方案
给Digulla先生一个正确的答案,因为这是与我的解决方案最相似的一个。还要感谢Davis先生,他让我明白了必须这样做的事实…二进制格式的格式是如何定义的。这给我带来了自定义序列化,并带来了同样的问题。使用BitConverter的100行,或者有更好的方法吗?是的!如果您可以解释如何使用托管引用类型在网络中执行此操作。您不能。您必须单独保存每个项,或使用序列化。我可以使用序列化定义输出二进制格式,而不必单独/手动保存每个项吗?您需要进一步解释。结构相同转换为源格式,而我不控制源(或格式)。
struct a * read_struct_a (stream in) {
struct a * result = malloc(sizeof(struct a));
read_int(in, &result->i);
return result;
}