[英]Trouble calling C++ code from MATLAB 2016 using a helper C file w/MEX Wrapper
我需要從MATLAB 2016調用C ++非成員函數。MATLAB直到2018年才支持C ++ MEX,因此這引起了問題。
我正在mingw64下的Windows中執行此操作。
為了解決這個問題,我嘗試使用MEX包裝器制作一個C文件,而C實現只是基於在線建議,使用帶有外部“ C”的共享頭文件來調用C ++函數。
但是,我對MATLAB非常陌生,在這里從C和其他一些概念調用C ++。 因此,任何東西都無法正確編譯。
非常感謝您提供有關正確解決此問題的建議。
頭文件myFunc.h:
#ifndef CPP_H
#define CPP_H
#ifdef __cplusplus
void myFunc(const std::vector<myStruct>& a,
const std::vector<myStruct>& b,
const double c,
std::vector<std::pair>& d,
mxArray **e
);
extern "C" {
#endif
void myFunc(const std::vector<myStruct>& a,
const std::vector<myStruct>& b,
const double c,
std::vector<std::pair>& d,
mxArray **e
);
#ifdef __cplusplus
}
#endif
#endif
調用它的C文件myFuncCaller.c:
#include "myFunc.h"
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
myFunc(prhs[0], prhs[1], prhs[2], prhs[3], prhs[4]);
}
實際實現:myFunc.cpp:
#include "myFunc.h"
void myFunc(const std::vector<myStruct>& a,
const std::vector<myStruct>& b,
const double c,
std::vector<std::pair>& d,
mxArray **e
)
{
//things done here, pushes results to d
}
嘗試同時編譯這兩者的最終結果是:
最大的障礙是從MATLAB-> C-> C ++傳遞輸入參數的方法。 我不希望事情“丟失”,理想情況下除非必要,否則不要進行轉換,而且我不確定那會在哪里。
您不能將std::vector<>
放在extern "C"
部分中,因為它不是有效的C語法。 您需要創建一個純C函數存根,將其編譯為C ++,然后調用C ++函數。
但是,您無需執行任何操作,因為您可以很好地編譯C ++ MEX文件。 該API是C,但是您可以從C ++調用C函數而不會出現問題。
在您的實際問題mexFunction
是您傳遞指針mxArray
的物件,函數需要引用std::vector<>
等做這一權利的唯一方法是將數據從MATLAB陣列復制到C ++向量:
#include "myFunc.h"
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs < 5) {
mexErrMsgTxt("Not enough input arguments! 5 expected.");
}
// arg 1: std::vector<myStruct>
if (!mxIsDouble(prhs[0])) {
mexErrMsgTxt("First input argument must be a double array.");
}
std::size_t N = mxGetNumberOfElements(prhs[0]);
double* pr = mxGetPr(prhs[0]);
std::vector<myStruct> a(N);
std::copy(pr, pr+N, a.begin());
// arg 2: std::vector<myStruct>
std::vector<myStruct> b;
// ...
// arg 3: double
double c = mxGetScalar(prhs[2]);
// arg 4: std::vector<std::pair> // This makes no sense in C++, std::pair<> is a template, 2 template arguments missing!!
std::vector<std::pair> d;
// ...
// arg 5: mxArray ** // is this the output? Why does your C++ function take an mxArray?
myFunc(a, b, c, d, &prhs[4]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.