涉及指针时如何 P/Invoke
在尝试学习在 C# 中使用 PInvoke 时,我有点不确定如何处理涉及简单值类型的指针的各种情况。
我从非托管 DLL 导入以下两个函数:
public int USB4_Initialize(short* device);
public int USB4_GetCount(short device, short encoder, unsigned long* value);
第一个函数使用指针作为输入,第二个函数使用指针作为输出。它们在 C++ 中的用法相当简单:
// Pointer as an input
short device = 0; // Always using device 0.
USB4_Initialize(&device);
// Pointer as an output
unsigned long count;
USB4_GetCount(0,0,&count); // count is output
我在 C# 中的第一次尝试产生了以下 P/Invokes:
[DllImport("USB4.dll")]
public static extern int USB4_Initialize(IntPtr deviceCount); //short*
[DllImport("USB4.dll")]
public static extern int USB4_GetCount(short deviceNumber, short encoder, IntPtr value); //ulong*
如何以与上面的 C++ 代码相同的方式在 C# 中使用这些函数? 是否有更好的方法声明这些类型的方法,也许使用MarshalAs
?
In an attempt to learn to use PInvoke in C#, I'm a little unsure how to handle various cases with pointers involving simple value types.
I'm importing the following two functions from an unmanaged DLL:
public int USB4_Initialize(short* device);
public int USB4_GetCount(short device, short encoder, unsigned long* value);
The first function uses the pointer as an input, the second as an output. Their usage is fairly simple in C++:
// Pointer as an input
short device = 0; // Always using device 0.
USB4_Initialize(&device);
// Pointer as an output
unsigned long count;
USB4_GetCount(0,0,&count); // count is output
My first attempt in C# results in the following P/Invokes:
[DllImport("USB4.dll")]
public static extern int USB4_Initialize(IntPtr deviceCount); //short*
[DllImport("USB4.dll")]
public static extern int USB4_GetCount(short deviceNumber, short encoder, IntPtr value); //ulong*
How do I use these functions in C# in the same way as the C++ code above? Is there a better way to declare these types, perhaps using MarshalAs
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果指针指向单个基本类型而不是数组,请使用 ref / out 来描述参数。
在这些示例中,out 可能更合适,但两者都可以。
If the pointer is to a single primitive type and not an array, use ref / out to describe the parameter
In these examples out is probably more appropriate but either will work.
.NET 运行时可以为您执行大量转换(称为“封送处理”)。虽然显式 IntPtr 始终会完全按照您的指示执行操作,但您可以用
ref
关键字替换这样的指针。然后你可以这样称呼它们:
The .NET runtime can do a lot of that conversion (referred to as "marshaling") for you. While an explicit IntPtr will always do EXACTLY what you tell it to, you can likely substitute the
ref
keyword for a pointer like that.You can then call them like this: