从用 C++ 编写的 DLL 调用自定义类型;来自 c#
我在我的 C# 项目中使用用 C++ 编写的 DLL。我已经能够使用以下代码调用 DLL 中的函数:
[DllImport("hidfuncs", EntryPoint = "vm_hid_scan", ExactSpelling = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr VmHidScan();
现在我需要调用一个需要自定义类型指针的函数。 DLL 的文档布局如下:
hid_get_info(int n,PDEV_INFO *pdi)
我不知道如何使用这个自定义指针。这是在DLL中定义的吗?如果是这样,如何从 C# 项目中使用它?如果没有,我需要在 c# 中包含头文件吗?预先感谢您的帮助。
I'm using a DLL written in c++ in my C# project. I have been able to call functions within the DLL using this code:
[DllImport("hidfuncs", EntryPoint = "vm_hid_scan", ExactSpelling = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr VmHidScan();
Now I need to call a function that requres a custom type pointer. The Docs for the DLL layout the function like this:
hid_get_info(int n,PDEV_INFO *pdi)
I don't know how to use this custom pointer. Is this defined in the DLL? If so how can use it from C# project? If not do I need to include the header file in c#? Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
给定“P”前缀,看起来真正的声明是
DEV_INFO 是一个结构。您需要找到此结构的声明,并使用 [StructLayout] 属性将其添加到 C# 代码中。然后,您可以在 C# 代码中声明如下函数:
并使用 Marshal.PtrToStructure() 获取结构值。希望你不必释放结构,否则你会被搞砸的。
第二种解释是“pid”返回指向 DEV_INFO 结构的指针数组。有点可能给出“n”参数,这很可能意味着您传递给函数填充的数组中的元素数量。在这种情况下,传递 IntPtr[] 并将“n”设置为其长度。
Given the "P" prefix, it looks like the real declaration is
where DEV_INFO is a structure. You'll need to find the declaration of this structure and add it to your C# code with the [StructLayout] attribute. You'd then declare the function like this in your C# code:
and use Marshal.PtrToStructure() to obtain the structure value. Hopefully you don't have to free the structure, you'd be screwed.
A second interpretation is that "pid" returns an array of pointers to DEV_INFO structures. Somewhat likely given the "n" argument, which could well mean the number of elements in the array you pass to be filled by the function. In that case, pass an IntPtr[] and set "n" to its Length.
您需要在 C# 中创建一个
struct
来镜像 C++ 中的 C++PDEV_INFO
struct
。您应该将
[StructLayout(LayoutKind.Sequential)]
应用于该结构,然后按顺序从 C++ 结构复制字段(查看头文件)。然后,您可以编写一个将
struct
作为ref
参数的extern
方法。You need to create a
struct
in C# that mirrors the C++PDEV_INFO
struct
in C++.You should apply
[StructLayout(LayoutKind.Sequential)]
to the struct and then copy the fields from the C++ struct (look at the header file) in order.You can then write an
extern
method that takes thestruct
as aref
parameter.我可以放心地假设
PDEV_INFO*
是DEV_INFO**
。在 C# 中使用它:
I'll safely assume
PDEV_INFO*
is aDEV_INFO**
.Use this in C#: