Windows フォーム アプリケーションで nlopt ライブラリ (http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial) を使用しようとすると、深刻な問題が発生します。コンソール アプリケーションで完全に動作する次の名前空間を作成しました。
#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 フォーム アプリケーションで使用しようとすると、問題が発生します。何らかの理由で「x」を空のポインターとして認識し、その場所にアクセスしようとするとエラーが発生する myfunc で常に未処理の例外が発生します。WindowsフォームがCLRを使用しているという事実が原因で問題が発生していると思いますが、解決できるかどうかはわかりません。Visual Studio 2008 を使用しており、テスト プログラムは単純なコンソール プロジェクト (正常に動作) と Windows フォーム プロジェクト (前述のエラーの原因) です。私のテスト コードは、提供されたリンクの C のチュートリアルに基づいています。私は、コンソール アプリケーションで再び正常に動作する C++ バージョンを試しましたが、Windows フォーム アプリケーションでデバッグ アサーションに失敗したというエラーが発生しました。
だから私の質問は次のとおりだと思います:私はWindowsフォームアプリケーションを使用しており、NLOptを使用したいと考えています。これを機能させる方法はありますか?