c# - 如何将 unsigned long * params 转换为 ulong[] params

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

我有一个非托管代码,它是一种类型:

unsigned long *inputParameters

我需要将我的变量输入参数转换为 C# 类型

 ulong[] inputParameters

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

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

但是我遇到了这个异常:

cannot convert argument from 'unsigned long *' to 'cli::array<unsigned __int64,1> ^'

最佳答案

在 C# 中称为引用类型的任何类型都需要使用 gcnew 实例化关键字,数组也不异常(exception)。大多数值类型都在幕后编排,因此您通常可以将 managed 分配给 unmanged ,反之亦然,而无需任何转换或欺骗。魔术,我知道!有一些异常(exception),但如果有问题,编译器会通知您。

我假设 *inputParameters是一个指针列表(而不是指向单个值的指针),这意味着您应该有一个包含列表中元素数量的变量,我们称它为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.

在这里,array<UInt64, 1>^是 C# 的 ulong[] 的 C++/CLI 等价物.你可以回managedArray到来自 C# 的方法调用,它需要 ulong[]作为返回类型。

关于c# - 如何将 unsigned long * params 转换为 ulong[] params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51646053/

相关文章:

c++ - 动态分配 std::unique_ptr 有什么用?

c# - 在 C++/CLI 中处理 C# 异常

c# - 如何将共享的 C# NuGet 依赖项添加到 C++/Cli 项目?

floating-point - C++/CLI : SIGFPE, _control87,_fpreset,将古老的不受管理的Watcom C应用程序移植到.NET

c++ - 简单的输入/输出控制台应用程序,不按给定顺序打印问题(结构性)

c# - 带空值的 EF Core 复合主键

c# - 获取包含枚举值的整数表示的字符串

c# - 如何异步运行每个任务并等待所有任务完成

c++ - Qt 中的屏幕录制

javascript - 使复选框成为一组单选按钮