Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当涉及指针时,如何P/Invoke_C#_Pinvoke_Dllimport - Fatal编程技术网

C# 当涉及指针时,如何P/Invoke

C# 当涉及指针时,如何P/Invoke,c#,pinvoke,dllimport,C#,Pinvoke,Dllimport,为了学习在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 sho

为了学习在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/调用:

[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++代码一样使用这些函数?<强>有更好的方法来声明这些类型,也许使用<代码> MARSARLAS < /C> > /P> < P>如果指针是单一的原始类型而不是数组,请使用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可能更合适,但两者都可以

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.

所以在GetCount()中,我可以使用out而不是ref?我明白了,这正是我所希望的。谢谢。是的,除了在USB4_GetCount定义中有外,P也会说同样的话嘿,USB4已经有了吗?我仍在等待3.0我希望如此。这与USB4无关。这只是公司用来连接编码器的USB设备,因为这是他们产品的第四版,他们愚蠢地将产品命名为USB4。