gpt4 book ai didi

c# - 如何在 C# struct 中声明和使用固定大小的 char 缓冲区

转载 作者:行者123 更新时间:2023-11-30 05:26:23 24 4
gpt4 key购买 nike

我有以下结构声明:

[StructLayout(LayoutKind.Sequential)]
public struct MyDLLInput
{
...
public fixed char PathtoData[256];
};

PathtoData 按原样显示错误:

"Pointers and fixed-size buffers may only be used in an unsafe context."

MyDLLInput 被传递给 C++ DLL:

public class MyDLL
{
[DllImport("MyDLL.dll",
EntryPoint = "?Unit@@YA?AUOutput@@UInput@@@Z",
CallingConvention = CallingConvention.Cdecl)]
public static extern MyDLLOutput Unit(MyDLLInput UnitInput);
}

MyDLL.h 将成员定义为:

char PathtoData[256];

如何在我的 C# 代码中正确地声明成员?

最佳答案

正如它所说:

Pointers and fixed-size buffers may only be used in an unsafe context.

因此,为了像这样使用固定大小的字符缓冲区,您需要将 unsafe 添加到您的结构中:

public unsafe struct MyDLLInput
{
...
public fixed char PathtoData[256];
};

您还需要允许这样的不安全编译:

  1. 右键单击您的项目。
  2. 选择“属性”。
  3. 切换到“构建”选项卡。
  4. 选中“允许不安全代码”

根据 MSDN - Unsafe Code and Pointers (C# Programming Guide)

In the common language runtime (CLR), unsafe code is referred to as unverifiable code. Unsafe code in C# is not necessarily dangerous; it is just code whose safety cannot be verified by the CLR. The CLR will therefore only execute unsafe code if it is in a fully trusted assembly. If you use unsafe code, it is your responsibility to ensure that your code does not introduce security risks or pointer errors.

有关安全和不安全代码的更多信息和比较,您还可以查看 Safe and Unsafe Code在 MSDN。

关于c# - 如何在 C# struct 中声明和使用固定大小的 char 缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37826673/

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