c# - 在 C# 中处理指向结构的指针

标签 c# c++ pointers memory dll

我正在开发一个项目,其中包括用 C++ 编写的 DLL 和一个 C# 代码。假设那个 DLL 有一个函数:

MyStruct* GetPointer(); // returns pointer to MyStruct structure

MyStruct 结构如下所示:

struct MyStruct
{
    OtherStruct1 *data1;
    OtherStruct2 *data2;
};

OtherStruct1 和 OtherStruct2 结构如下所示:

struct OtherStruct1
{
public:
    double x;
    char y;
};

struct OtherStruct2
{
public:
    float a;
    float b;
    float c;
    float d;
};

我的问题是 - 在 C# 代码中处理所有这些指针的最佳方式是什么? “处理”是指读取和写入内存的操作。 C# 中的结构不能简单地包含指针变量。我应该做些什么?什么是最优雅的方式?

最佳答案

好的,我重新设计了一种方法。

[StructLayout(LayoutKind.Sequential)]
struct MyStruct
{
    OtherStruct1 *data1;
    OtherStruct2 *data2;
};

[StructLayout(LayoutKind.Sequential)]
struct OtherStruct1
{
public:
    double x;
    char y;
};

[StructLayout(LayoutKind.Sequential)]
struct OtherStruct2
{
public:
    float a;
    float b;
    float c;
    float d;
};

然后:

unsafe
{
    MyStruct *tmp = (MyStruct*) GetPointer();
    tmp->data2[0].a = 1.0F;
}


[DllImport(DLL_PATH, CallingConvention = CallingConvention.Cdecl)]
    unsafe public static extern MyStruct* GetPointer();

像魅力一样工作。 :)

关于c# - 在 C# 中处理指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40495321/

相关文章:

c# - 在 C# 中,从实际上充满子项的 List<Parent> 中,如何访问这些子项的特定构造函数?

c++ - 为什么相同的 gcc 编译选项在不同的计算机体系结构上会有不同的表现?

c++ - 将持续时间添加到 C++ 时间点

objective-c - Objective-c 上的指针

c - 当存储非指针值时,C 中实际上发生了什么?

c# - 从被调用函数中获取调用函数名

c# - 将哈希表添加到另一个哈希表的末尾

c# - 一旦 frame 导航到另一个 Page 就销毁 ViewModel 和 Page 的实例

c++ - 如何设置函数指针参数以便它接受任何东西

c - 指向接收不需要的垃圾值的单独函数中的数组的指针