C++ 使用windows窗体进行NLOpt
我在尝试使用nlopt库时遇到了严重的问题(http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial)在windows窗体应用程序中。我创建了以下名称空间,它可以在控制台应用程序中完美运行C++ 使用windows窗体进行NLOpt,c++,clr,nlopt,C++,Clr,Nlopt,我在尝试使用nlopt库时遇到了严重的问题(http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial)在windows窗体应用程序中。我创建了以下名称空间,它可以在控制台应用程序中完美运行 #include "math.h" #include "nlopt.h" namespace test { typedef struct { double a, b; } my_constraint_data;
#include "math.h"
#include "nlopt.h"
namespace test
{
typedef struct {
double a, b;
} my_constraint_data;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int comp()
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
nlopt_set_xtol_rel(opt, 1e-4);
double x[2] = { 1.234, 5.678 }; /* some initial guess */
double minf; /* the minimum objective value, upon return */
int a=nlopt_optimize(opt, x, &minf) ;
return 1;
}
}
它优化了简单的非线性约束最小化问题。当我尝试在windows窗体应用程序中使用此命名空间时,问题就出现了。我经常在myfunc中遇到未处理的异常,由于某种原因,它将“x”视为空指针,因此在尝试访问其位置时会导致错误。我相信这个问题是由于windows窗体使用CLR造成的,但我不知道它是否可以解决。我使用的是VisualStudio2008,测试程序是简单控制台项目(工作正常)和windows窗体项目(导致上述错误)。
我的测试代码基于所提供链接中的C教程。虽然我尝试了C++版本,它在控制台应用程序中再次工作,但在Windows窗体应用程序中调试错误失败。
所以我想我的问题是:我有一个windows窗体应用程序,我想使用NLOpt。有什么办法可以做到这一点吗?我不知何故在开头漏掉了Hello,在结尾漏掉了Thank,由于某种原因,我无法编辑我的消息,因此我现在正在修复它,并对我的不礼貌表示歉意:)C++/CLI编译器将此C代码转换为IL不会有问题。但是调用约定是错误的,是clrcall而不是cdecl。因此,这些论点是错误的。您需要关闭此代码的/clr编译选项。好极了。我欠你们一个:我真的很难理解C++内部结构。你介意提供一些帮助你理解它的文献或网站吗?