为了学习在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
?
答案 0 :(得分:12)
如果指针指向单个基本类型而不是数组,请使用ref / out来描述参数
[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)
在这些例子中,可能更合适,但两者都可行。
答案 1 :(得分:0)
.NET运行时可以为您完成大量的转换(称为“编组”)。虽然明确的IntPtr将始终完全按照您的说法进行操作,但您可以将ref
关键字替换为类似指针。
[DllImport("USB4.dll")]
public static extern int USB4_Initialize(ref short deviceCount); //short*
[DllImport("USB4.dll")]
public static extern int USB4_GetCount(short deviceNumber, short encoder, ref short value); //ulong*
然后你可以这样打电话给他们:
short count = 0;
USB4_Initialize(ref count);
// use the count variable now.