将结构编组为非托管数组

发布于 2024-08-27 05:23:41 字数 477 浏览 3 评论 0原文

我有一个 C# 结构体来表示笛卡尔向量,如下所示:

public struct Vector  
{  
    private double x;  
    private double y;  
    private double z;  

    //Some properties/methods
}

现在我有一个非托管 C dll,需要使用 P/Invoke 进行调用。某些方法需要 double[3] 参数。

非托管 C 签名类似于

void Cross(double a[3], double b[3], double c[3]);  

是否有任何方法可以设置 P/Invoke 签名,以便我可以传递 Vector 结构的实例并将它们透明地封送到非托管 double[3]?我还需要双向封送,因为非托管函数需要将输出写入参数数组,所以我想我需要封送为 LpArray。

I have a C# struct to represent a cartesian vector, something like this:

public struct Vector  
{  
    private double x;  
    private double y;  
    private double z;  

    //Some properties/methods
}

Now I have an unmanaged C dll that I need to call with P/Invoke. Some methods expect a double[3] parameter.

The unmanaged C signature is something like

void Cross(double a[3], double b[3], double c[3]);  

Is there any way to set up a P/Invoke signature so I can pass instances of my Vector struct and marshal them transparently to unmanaged double[3]? I would also need bidirectional marshaling as the unmanaged function needs to write the output to the argument array, so I guess I would need to marshal as LpArray.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

べ映画 2024-09-03 05:23:41

您可以在 P/Invoke 声明中撒谎,成员将在所有当前 CPU 架构上正确对齐,以便在非托管代码中作为数组读取:

[DllImport("blah.dll")]
private static extern void Cross(ref Vector a, ref Vector b, ref Vector c);

You can lie in your P/Invoke declaration, the members will align properly on all current CPU architectures to be readable as an array in unmanaged code:

[DllImport("blah.dll")]
private static extern void Cross(ref Vector a, ref Vector b, ref Vector c);
顾冷 2024-09-03 05:23:41

我手边没有编译器,但我想知道您是否可以使用类似的东西

[MarshalAs(...)]
[StructLayout(LayoutKind::Sequential, Pack=1)]
public struct Vector  
{  
    private double x;  
    private double y;  
    private double z;  

    //Some properties/methods
}

参见 此处此处此处

I don't have my compilers to hand, but I wonder if you can use something like

[MarshalAs(...)]
[StructLayout(LayoutKind::Sequential, Pack=1)]
public struct Vector  
{  
    private double x;  
    private double y;  
    private double z;  

    //Some properties/methods
}

See here and here and here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文