将结构编组为非托管数组
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 P/Invoke 声明中撒谎,成员将在所有当前 CPU 架构上正确对齐,以便在非托管代码中作为数组读取:
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:
我手边没有编译器,但我想知道您是否可以使用类似的东西
参见 此处和此处 和此处
I don't have my compilers to hand, but I wonder if you can use something like
See here and here and here