p/invoke 返回指向结构体指针的 C 函数
如何在 C# 中声明返回指向结构的指针的 C 函数?
我相信以下是一种方法,然后是 Marshal.PtrToStructure 来获取实际的结构值。
// C-function
SimpleStruct * Function(void);
// C# import
[DllImport("MyDll.dll")]
public static extern IntPtr Function();
- 我的说法正确吗?
- 还有其他方法可以完成同样的任务吗? (按值获取结构就可以了)
How do I declare in C# a C function that returns a pointer to a structure?
I believe following is one way to do that, followed by Marshal.PtrToStructure to get actual structure value.
// C-function
SimpleStruct * Function(void);
// C# import
[DllImport("MyDll.dll")]
public static extern IntPtr Function();
- Am I correct about that?
- Are there other ways to accomplish the same? (It would be OK to get struct back by value)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于该函数返回一个指针(希望不是本地分配的指针?),您最好的选择是手动封送它(通过 Marshal.PtrToStructure)。
如果它是一个参数,您可以使用 PInvoke Interop Assistant 创建该结构的托管版本,然后通过 ref 或 out 传递它。
Since the function returns a pointer (hopefully not a locally allocated one?) your best bet is to manually marshal it (via Marshal.PtrToStructure).
If it were a parameter you could create a managed version of the structure using the PInvoke Interop Assistant then pass it via ref or out.
警告:只有当返回的指针指向已由 CLR 管理的内存时,这才有效
我相信您正在寻找的是
这应该消除对任何手动
Marshal.PtrToStructure
的需要> 来电。 根据您的结构包含的内容,您可能需要根据需要使用MarshalAs
属性标记某些字段。 MSDN 有一个很好的例子。Caveat: this will only work if the pointer returned is to memory already managed by the CLR
I believe what you are looking for is
This should eliminate the need for any manual
Marshal.PtrToStructure
calls. Depending on what your structure contains, you may need to tag some fields withMarshalAs
attributes as appropriate. MSDN has a good example of this.我根本不是这里的专家,但我碰巧正在查看一段代码(请注意,我完全不理解)正在做同样的事情。
这是他们正在做的事情
,然后在结构上他们具有以下属性,
我认为您正在寻找的部分是 [In,Out] 部分,并且由于它是通过 ref 传递的,因此您应该得到相同的数据。
标记为社区 wiki,以便人们可以在错误时修复此问题。
I am not an expert here at all, but I happened to be looking at a piece of code (that i don't understand completely mind you) that is doing this same thing.
Here is what they are doing
and then on the structure they have the following attribute
I think the part you are looking for is the [In,Out] part, and since it's being passed via ref, you should be getting the same data back.
marked as community wiki so people can fix this if wrong.