【发布时间】:2016-01-25 11:29:50
【问题描述】:
与问题中的完全一样。
我有一对库,一个在 cpp 中,另一个在 c# 中。我已经有几个可以从 c# 调用的 (cpp) 函数,但只能使用简单的参数(数组和原语)。
如何传递函数?
我在这里阅读了大量答案,但没有一个能帮助我 - 我错过了什么?
这就是我所拥有的:
delegate double ManagedFunction(cli::array<System::Double>^ xIn);
...
...
static int LevMar(
ManagedFunction^ function,
cli::array<System::Double, 1>^ x0,
cli::array<System::Double, 1>^ xHigh,
cli::array<System::Double, 1>^ xLow,
int maxIters//,
//double tolerance
) {
IntPtr stubPointer = Marshal::GetFunctionPointerForDelegate(function);
Unmanaged::WrapperClass::functionToMinimize = static_cast<Unmanaged::UnmanagedFunction>(stubPointer.ToPointer());
int m = x0->Length; //nDim
int N = 1; //observables dimension
double* fx = new double[m];
double* x0Arr = Utility::CreateDoubleArrayFromManaged(x0);
double* xLowArr = Utility::CreateDoubleArrayFromManaged(xLow);
double* xHighArr = Utility::CreateDoubleArrayFromManaged(xHigh);
double info[LM_INFO_SZ];
double tolerance[5];
tolerance[0] = 0.01; //scale factor for initial \mu/
tolerance[1] = tolerance[2] = tolerance[3] = tolerance[4] = 1.0e-5;
dlevmar_bc_dif(Unmanaged::WrapperClass::functionToPassToLevMar, x0Arr, fx, m, N, xLowArr, xHighArr, NULL, maxIters, tolerance, info, NULL, NULL, NULL);
int nElements = sizeof x0Arr / sizeof x0Arr[0];
for (int i = 0; i < nElements; i++) x0[i] = x0Arr[0];
return 0;
}
这一切都编译了,但我还不能测试它,因为我不能从 c# 调用它;这是我尝试过的:
CostDelegate costDelegate = new CostDelegate(cost);
XXXCpp.Minimization.LevMar(costDelegate, x0, xhigh, xlow, 1000);
但它告诉我它不能从“CostDelegate”转换为“ManagedFunction”。两者都是代表,并且都具有相同的签名。
我怎样才能在这里实现我想要的?
有没有办法做到这一点,以便在 c# 中,当我调用函数时,我可以将函数传递给它,而不必创建委托(即,我可以编写 cpp 以使函数采用 @987654323 @ 而不是这个 'ManagedFunction' 对象)?
【问题讨论】:
-
从您的代码中不是很清楚您要做什么。例如。 Unmanaged::WrapperClass::functionToPassToLevMar 的类型是什么以及分配的位置。你能提供一个不依赖其他类的更简单的例子吗?
标签: c# c++ function delegates c++-cli