与问题完全相同。如何创建一个可以从c#调用的cpp函数作为参数
我有一对库,一个在cpp中,另一个在c#中。我已经有几个(cpp)函数可以从c#调用,但只有简单的参数(数组和基元)。
如何传递函数?
我已经阅读了大量的答案在这里,他们都没有帮助我 - 我失踪了什么?
下面是我有:
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,使功能需要Func<double[], double>
而不是这个'ManagedFunction'对象)?
从你的代码不是很清楚你想要做什么。例如。它们是什么类型的Unmanaged :: WrapperClass :: functionToPassToLevMar以及它分配的位置。你能否提供一个简单的例子,而不依赖于其他类? – opetroch