加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在涉及指针时进行P / Invoke

发布时间:2020-12-15 08:06:31 所属栏目:百科 来源:网络整理
导读:为了学习在C#中使用PInvoke,我有点不确定如何处理涉及简单值类型的指针的各种情况. 我从非托管DLL导入以下两个函数: public int USB4_Initialize(short* device);public int USB4_GetCount(short device,short encoder,unsigned long* value); 第一个函数使
为了学习在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,&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,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,ref uint32 value)

在这些例子中,可能更合适,但两者都可行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读