Matlab Engine による Cプログラムとの連携

4 visualizzazioni (ultimi 30 giorni)
kota kobayashi
kota kobayashi il 6 Dic 2018
Commentato: Kojiro Saito il 7 Dic 2018
Matlabのプログラムを作り、名前をTest.mとしてデスクトップに保存します。
次に、このプログラム内で計算した整数値 t を、Matlab Engineを利用して取り出して表示する、最も簡単なCプログラムのコードを作りました。
#include <stdio.h>
#include <conio.h>
#include "engine.h"
#pragma comment(lib,"libeng.lib")
#pragma comment(lib,"libmx.lib")
int main()
{
Engine *ep;
mxArray *t ;
ep = engOpen(NULL);
engEvalString(ep, "cd 'C:\Users\user1802\Desktop\source1810'");
engEvalString(ep, "MatlabEngineTest");
engEvalString(ep, "disp(t)");
t = engGetVariable(ep, "t");
t_real = mxGetPr(t);
printf("%f\n", t_real[0]);
engClose(ep);
system("pause");
return 0;
}
このコードをVisual Stadio Community 2015 Version 14.0.25431.01 Update 3でデバッグしたところ、以下のエラーが出ました。
「0x00007FF7796B18C7 で例外がスローされました (Matlab_Engine.exe 内): 0xC0000005: 場所 0x0000000000000000 の読み取り中にアクセス違反が発生しました
この例外のハンドラーがある場合は、プログラムを安全に続行できます。」
値tを取得できていないみたいなのですが、コードに欠陥があるのか、環境の問題かわかりません。(そもそもmatlabのプログラムを実行できていない?)
助言をお願いします。

Risposta accettata

Kojiro Saito
Kojiro Saito il 6 Dic 2018
Visual Studioのターゲットプラットフォームはx64になっていますか?
x64にしてもエラーが出る場合、デバッグ時にengOutputBufferを入れてみると良いですよ。MATLAB上の画面出力が文字列として保存されますので、Cコード上でもpritnfで確認できます。Cコードに以下のコードを入れてみると原因が分かります。
% 前略
#define BUFSIZE 256
% 中略
int main()
{
% 中略
char buffer[BUFSIZE + 1];
buffer[BUFSIZE] = '\0';
% 中略
engOutputBuffer(ep, buffer, BUFSIZE);
printf("%s\n", buffer);
% 中略
}
これを付けた上で、私の環境でご質問に載っているCコードを実行したところ、tが未定義というエラーが出ていました。カレントディレクトリがおかしいのかと思い、以下の内容をCコードに追加したところ、
engEvalString(ep, "pwd");
pwdがMATLAB_INSTALL\bin\win64 になっていました。cdに失敗しています。
上記のコードのcdのところで、フォルダのパスをシングルクォーテーションでくくるのではなく、バックスラッシュを2つ重ねてエスケープしてみるとcdに成功します。
// engEvalString(ep, "cd 'C:\Users\user1802\Desktop\source1810'");
engEvalString(ep, "cd C:\\Users\\user1802\\Desktop\\source1810");
あと、実行結果をprintfするところも、そのままではうまくいかなかったので以下のように変更してみてください。
// t_real = mxGetPr(t);
// printf("%f\n", t_real[0]);
double t_real = *mxGetPr(t);
printf("%f\n", t_real);
  2 Commenti
kota kobayashi
kota kobayashi il 7 Dic 2018
できました!これは自力ではできなかったです。
ありがとうございました。
Kojiro Saito
Kojiro Saito il 7 Dic 2018
解決できて良かったです!

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!