小编ASi*_*ner的帖子

struct c#中的安全固定大小数组

我在嵌入式 MCU 中有一个 C 结构,大约有 1000 个元素,其中包含许多固定大小的数组和其他结构,现在我想使用 C# 将数据传送到 PC

这是我在 C 中的结构元素的简单预览

struct _registers
{
    char name[32];
    float calibrate[4][16];
    float DMTI;
    float DMTII;
    float DMTIII;
    float DMTIE;
    float DMTIIE;
    ....
};
Run Code Online (Sandbox Code Playgroud)

现在我想使用 GCHandle 类将 Struct 转换为 C#,

像这样的东西

//The C struct is in this byte array named buffer
byte[] buffer = new byte[4096];

        GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
       _registers stuff = (protection_registers)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(_registers));
        handle.Free();
Run Code Online (Sandbox Code Playgroud)

问题是 Visual Studio 抱怨“指针和固定大小的缓冲区只能在不安全的上下文中使用”

有没有办法在没有不安全代码的情况下正常使用它?我发现做这样的事情

[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{ …
Run Code Online (Sandbox Code Playgroud)

c# arrays struct

3
推荐指数
1
解决办法
8359
查看次数

标签 统计

arrays ×1

c# ×1

struct ×1