繁体   English   中英

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

[英]How To Marshal Int Arrays Or Pointers To Int Arrays

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

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

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

在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);

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

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

它是:

[DllImport(dllName, CallingConvention=CallingConvention.StdCall)]
static extern void ReadStuff(int id, int[] buffer);

封送处理程序将执行“正确的”操作。

要么

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

但是使用起来比较复杂。

CallingConvention=CallingConvention.StdCall是默认设置,因此无需明确将其写出。

您使用这种方式:

// call
int[] array = new int[12];
ReadStuff(1, array);

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

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

您可以执行以下操作:

[DllImport(dllName)]
static extern void ReadStuff(int id, IntPtr buffer, int length);


int[] array = new int[12];

unsafe
{
  fixed (int* data = &array[0])
    ReadStuff(1, (IntPtr)data, array.Length);
}

C ++代码:(未经测试)

extern "C" __declspec(dllexport) VOID WINAPI ReadStuff(int id, int* buffer, int length);  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM