在尝试学习在 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
?