如何封送诠释数组或指针数组INT [英] How To Marshal Int Arrays Or Pointers To Int Arrays

查看:126
本文介绍了如何封送诠释数组或指针数组INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我用C#的工作我有一个第三方 DLL 需要INT阵列(或指针int数组)作为参数。我如何编组C#和C / C之间的int数组++?该函数声明如下:

I'm working with C# an I have a third party dll that needs int arrays (or pointers to int array) as parameters. How do I marshal an int array between C# and C/C++ ? The functions are declared like this:

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

在C 为int * 将是一个指针吧?所以我很困惑,如果我不得不使用的IntPtr 或者如果我可以使用 INT [] (preferred )?我想这可能是确定:

In C int* would be a pointer right ? So I'm confused if I have to use IntPtr or if I could use int[] (preferred) ? I thought this might be ok:

[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#中此功能在安全code?

Would that work ? Or how do I have to declare this function in C# in safe code ?

推荐答案

这不是一个SAFEARRAY。一个SAFEARRAY是连接东西变式和OLE的美好时光:-)它可能生活在单词渡渡鸟。

It isn't a SafeArray. A SafeArray is something connected to Variants and the good old times of OLE :-) It probably lives in the dictionary near the word "dodo".

有:

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

在编组会做正确的事情。

the marshaler will do the "right" thing.

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

但它更复杂的使用。

but then it's more complex to use.

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

The CallingConvention=CallingConvention.StdCall is the default one, so it isn't necessary to write it out explicitly.

您用这种方式:

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

A REF INT [] 将是 INT ** (但它可能是复杂的传递,因为通常您会收到数组,而不是发送阵列:-))

A ref int[] would be a int** (but it could be complex to pass, because normally you RECEIVE the array, not SEND the array :-) )

请注意,你的接口,是相当差:你不能告诉 ReadStuff 您的缓冲区的长度,也不能接收缓冲区的长度需要,也不能接收真的使用的缓冲器的字符数。

Note that your "interface" is quite poor: you can't tell to ReadStuff the length of your buffer, nor can you receive the necessary length of the buffer, nor can you receive the number of characters of the buffer that were really used.

这篇关于如何封送诠释数组或指针数组INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆