在C和C#之间交换结构(涉及到其他结构的指针) [英] Exchange structures (envolving pointers to other structures) between C and C#
问题描述
我想使用PInvoke将以下内容带给托管方:
I want to use PInvoke to bring to managed side something this:
(C代码)
typedef struct {
//一些字段...
} 一种;
typedef struct{
//some fields...
} A;
类型struct {
A * a;
} B;
type struct{
A* a;
} B;
int getB(B * destination){//目标将是C#的输出参数.
//将B放入目的地"
返回0;
}
int getB(B* destination){ //destionation will be an output parameter to C#
//puts an B in 'destination'
return 0;
}
现在,我需要一种方法来告诉托管方如何将B从C编组为C#结构或类.我尝试了很多事情,例如IntPtr字段,MarchalAs属性,但没有成功.我不会在这里公开我试图保持问题简单的代码.但是,只要有较长的答案,我就可以做到.
Now, I need a way to tell managed side how to marshalling B from C to C# structure or class. I've tryed many things such as IntPtr fields, MarchalAs atributes, but with no success. I will not expose here the code that I've tryed to keep the question simple. However i could do it as long answers arrive.
推荐答案
您可以使用元帅类来做到这一点.
You can do that using the Marshal class.
// Define a C# struct to match the unmanaged one
struct B
{
IntPtr a;
}
[DllImport("dllName")]
extern int getB(IntPtr destination);
B GetB()
{
IntPtr ptrToB = IntPtr.Zero;
getB(ptrToB);
return (B)Marshal.PtrToStructure(ptrToB, typeof(B));
}
这篇关于在C和C#之间交换结构(涉及到其他结构的指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!