簡體   English   中英

使用帶有MEX包裝器的輔助C文件從MATLAB 2016調用C ++代碼時遇到問題

[英]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
}

嘗試同時編譯這兩者的最終結果是:

  • C文件看不到mex.h(不確定原因,因為MATLAB聲稱mingw是抱怨)
  • 頭文件可能全錯了,並聲稱“類型聲明中的類型默認為int”。 我假設這是因為我在C部分中有一些與C ++相關的東西。 我不確定該如何處理。
  • C ++文件抱怨最多。 我可以發布所有錯誤,但考慮到我的邏輯中可能存在根本性缺陷,我認為這樣做不會有效果。

最大的障礙是從MATLAB-> C-> C ++傳遞輸入參數的方法。 我不希望事情“丟失”,理想情況下除非必要,否則不要進行轉換,而且我不確定那會在哪里。

  1. 您不能將std::vector<>放在extern "C"部分中,因為它不是有效的C語法。 您需要創建一個純C函數存根,將其編譯為C ++,然后調用C ++函數。

  2. 但是,您無需執行任何操作,因為您可以很好地編譯C ++ MEX文件。 該API是C,但是您可以從C ++調用C函數而不會出現問題。

  3. 在您的實際問題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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM