是的,需要的东西听起来很简单,但事实证明这是一个真正的痛苦。
我在 C# 中有一些 GUI 代码(注意我以前从未使用过 C# 但熟悉语法)并且我有 C++ 代码与它交互使用 < strong>CLI.
在 C# 中,我想创建一个 double 组,并将其发送到我的 C++ 代码。我使用下面的代码作为传递数组的方式,并且它独立地符合要求。
所以我从 C# 中将一个 double [] 数组传递给该函数。
public ref class KernelWrapper
{
public:
static void ImageNoiseFilter(System::IntPtr imageData, int imageWidth, int imageHeight, array<double>^ values);
我应该使用什么参数类型从 C++ 端检索此数组?
我试过:
MyFunction(double values[]){}
MyFunction(double* values){}
MyFunction(array<double>^ values){}
但没有编译,最后一个通常带有“array is not a template”的消息,并且
Error 1 error C2664: 'RunImageNoiseFilterKernel' : cannot convert parameter 4 from 'cli::array<Type> ^' to 'double *'
任何有关如何实现这一目标的提示都将不胜感激。
为了可读性,我在这里更新了代码
.cpp文件:
void Bangor::KernelWrapper::ImageNoiseFilter(System::IntPtr imageData, int imageWidth, int imageHeight, pin_ptr<double> pval){
RunImageNoiseFilterKernel((Format24bppRgb*)((int)imageData), imageWidth, imageHeight); //If parameter would work, 4th argument would also be passed into this.
}
C#代码:
double[] randomValues = new double[ARRAY_LENGTH]; //Array of random numbers
KernelWrapper.ImageNoiseFilter(ptr, image.Width, image.Height, randomValues);
错误是:
Error 1 error C3824: 'cli::pin_ptr<Type>': this type cannot appear in this context (function parameter, return type, or a static member)
Error 3 The best overloaded method match for 'Bangor.KernelWrapper.ImageNoiseFilter(System.IntPtr, int, int, double*)' has some invalid arguments
Error 4 Argument 4: cannot convert from 'double[]' to 'double*'
希望这能澄清一点。
最佳答案
你应该使用 pin_ptr<> class将托管数组转换为 double*。它固定数组,因此当您的 native 函数正在执行和访问数组数据时,垃圾收集器无法移动它。
#include <vcclr.h> // Declares cli::pin_ptr<>
using namespace cli;
#pragma managed(push, off)
# include "unmanagedstuff.h" // Declaration of MyFunction here
#pragma managed(pop)
...
pin_ptr<double> pvalues = &values[0];
MyFunction(pvalues, values->Length);
假设 MyFunction() 肯定也需要知道数组的大小,所以我添加了一个额外的参数来传递数组的大小。不这样做是致命的,您的 native 代码很容易破坏托管堆的完整性。请注意,只有当 pvalues 在范围内时,数组才会保持固定状态,因此 MyFunction() 不 存储传递的指针很重要。如果是这种情况,那么您必须复制数组。
关于c# - 使用 CLI 将 C# double 组传递给 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15461280/