涉及指针时如何P/调用 [英] How to P/Invoke when pointers are involved
问题描述
为了尝试在C#中使用PInvoke,我有点不确定如何使用涉及简单值类型的指针处理各种情况.
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.
我要从非托管DLL导入以下两个函数:
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);
第一个函数使用指针作为输入,第二个函数使用输出.在C ++中,它们的用法非常简单:
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
我第一次尝试C#会导致以下P/调用:
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*
如何以与上述C ++代码相同的方式在C#中使用这些函数?是否有更好的方法来声明这些类型,也许使用MarshalAs
?
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
?
推荐答案
如果指针指向单个基本类型而不是数组,请使用ref/out来描述参数
If the pointer is to a single primitive type and not an array, use ref / out to describe the parameter
[DllImport("USB4.dll")]
public static extern int USB4_Initialize(ref short deviceCount);
[DllImport("USB4.dll")]
public static extern int USB4_GetCount(short deviceNumber, short encoder, ref uint32 value)
在这些示例中,输出可能更合适,但任何一个都可以.
In these examples out is probably more appropriate but either will work.
这篇关于涉及指针时如何P/调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!