11

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

4

2 回答 2

17

如果指针指向单个原始类型而不是数组,请使用 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)

在这些示例中, out 可能更合适,但两者都可以。

于 2009-09-14T16:55:11.793 回答
1

.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.
于 2009-09-14T16:56:37.560 回答