我在内存中有一个二进制序列化对象,我想通过使用 C# 中的指针(不安全代码)从内存中读取它。请看以下从内存流读取的函数。
static Results ReadUsingPointers(byte[] data)
{
unsafe
{
fixed (byte* packet = &data[0])
{
return *(Results*)packet;
}
}
}
在这个return *(Results*)packet;
语句中,我得到一个编译时异常“无法获取托管类型的地址、获取其大小或声明指向托管类型的指针结果”
这是我的结构
public struct Results
{
public int Id;
public int Score;
public char[] Product;
}
根据我的理解,我的结构的所有属性都是 blittable 属性,那么为什么我会收到此错误,如果我需要在结构中使用 char[] 我该怎么办?
EDIT-1 让我进一步解释(请注意,对象是模拟的)...
背景:
我有一个 Results
对象数组,我使用二进制序列化来序列化它们。现在,在程序的后期阶段,由于数据量非常大,我需要尽快反序列化内存中的数据。所以我正在尝试,不安全的代码可以如何帮助我。
假设我的结构不包含 public char[] Product;
,我会以相当快的速度取回数据。但是对于 char[] 它给了我错误(编译器应该这样做)。我一直在寻找一种在这种情况下与 char[] 配合使用的解决方案。
最佳答案
Any of the following types may be a pointer type:
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
Any enum type.
Any pointer type.
Any user-defined struct type that contains fields of unmanaged types only.
因此,您可以按如下方式定义结构来修复编译器错误:
public struct Results
{
public int Id;
public int Score;
// Don't actually do this though.
public unsafe char* Product;
}
这样,您就可以指向数组的第一个元素。
但是,根据您编辑的问题,您需要采用不同的方法。
I have an array of Results objects, I serialized them using binary serialization. Now, at later stages of my program, I need to de-serialize my data in memory as quickly as possible
通常您会使用 BinaryFormatter
来实现此目的。如果这太慢,那么问题应该是是否可以首先避免序列化。
关于c# - 不安全代码中的错误,使用指针读取内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23191843/