如何封送Int数组或指向Int数组的指针

Bit*_*lue 5 c c# arrays marshalling

(我知道这可能是重复的,但我不理解其他线程)

我正在使用C#,我有一个dll需要将int数组(或指向int数组的指针)作为参数的第三方。如何在C#和C / C ++之间封送一个int数组?函数声明如下:

// reads/writes int values from/into the array
__declspec(dllimport) void __stdcall ReadStuff(int id, int* buffer);
Run Code Online (Sandbox Code Playgroud)

在C中int*会是指针吗?所以我很困惑是否必须使用IntPtr或可以使用int[](首选)?我认为这可能没问题:

[DllImport(dllName)]
static extern void ReadStuff(int id, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_I4)] ref int[] buffer);

// call
int[] array = new int[12];
ReadStuff(1, ref array);
Run Code Online (Sandbox Code Playgroud)

那行得通吗?还是我必须以安全代码在C#中声明此函数?

xan*_*tos 5

它不是一个 SafeArray。SafeArray 与 Variants 和 OLE 的美好时光有关 :-) 它可能存在于字典中的“dodo”一词附近。

这是:

[DllImport(dllName, CallingConvention=CallingConvention.StdCall)]
static extern void ReadStuff(int id, int[] buffer);
Run Code Online (Sandbox Code Playgroud)

marshaler 会做“正确”的事情。

或者

[DllImport(dllName, CallingConvention=CallingConvention.StdCall)]
static extern void ReadStuff(int id, IntPtr buffer);
Run Code Online (Sandbox Code Playgroud)

但是使用起来更复杂。

CallingConvention=CallingConvention.StdCall是默认的,所以没有必要把它明确地写出来。

你用这种方式:

// call
int[] array = new int[12];
ReadStuff(1, array);
Run Code Online (Sandbox Code Playgroud)

Aref int[]将是一个int**(但传递可能很复杂,因为通常您接收数组,而不是发送数组:-))

请注意,您的“接口”很差:您无法知道ReadStuff缓冲区的长度,也无法接收缓冲区的必要长度,也无法接收实际使用的缓冲区的字符数。