涉及指针时如何 P/Invoke

2023-12-26

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


如果指针指向单个基本类型而不是数组,则使用 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 可能更合适,但两者都可以。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

涉及指针时如何 P/Invoke 的相关文章

随机推荐