如何将无符号long *参数转换为ulong []参数

时间:2018-08-02 05:23:49

标签: c# c++ c++-cli unmanaged managed

我有一个非托管代码,其类型为:

 ulong[] inputParameters

我需要将变量inputparameters转换为C#类型

auto inputParams = *((unsigned long*)inputParameters)
&inputParameters

我尝试了不同类型的转化,例如

{{1}}

但是我遇到此异常:

  

无法将参数从'unsigned long *'转换为'cli :: array ^'

1 个答案:

答案 0 :(得分:1)

在C#中称为引用类型的任何类型都需要使用gcnew关键字实例化,数组也不例外。大多数值类型在幕后都会被编组,因此您通常可以将托管类型分配给未管理类型,反之亦然,而无需进行任何强制或欺骗。魔术,我知道!有一些例外,但是编译器会在出现问题时通知您。

我假设*inputParameters是一个指针列表(而不是指向单个值的指针),这意味着您应该有一个包含列表中元素数量的变量,将其命名为{{ 1}}。要进行转换,您可以执行以下操作:

nElements

在这里,//some test data int nElements = 10; unsigned long *inputParameters = (unsigned long *)malloc(sizeof(unsigned long) * nElements); for (int i = 0; i < nElements; i++) { *(inputParameters + i) = i * 2;//just arbitrary values } //now create a .NET array (lines below directly solve your question) array<UInt64, 1>^ managedArray = gcnew array<UInt64, 1>(nElements); for (int i = 0; i < nElements; i++) { tempArray[i] = *(inputParameters + i);//this will be marshalled under the hood correctly. } //now the array is ready to be consumed by C# code. 与C#的array<UInt64, 1>^等效。您可以将ulong[]返回到C#的方法调用中,该方法期望managedArray为返回类型。