【发布时间】:2019-03-26 16:52:58
【问题描述】:
我目前正在尝试优化我在 MATLAB(版本 R2019a)中处理的一些代码。为了计算我的结果,MATLAB 必须多次计算某个函数,从而减慢一切速度。因此,我认为用 C 语言编写这个函数并将其导入 MATLAB 会大大加快速度。不幸的是,我尝试使用 MEX 将 C 代码编译到 MATLAB 中遇到了一些麻烦。
我以前用过 C,但肯定不是专家。无论如何,我已经在 C 中测试了代码并且它可以工作,问题在于尝试在 MATLAB 中编译代码。我正在使用 GNU 科学库 (GSL),因此应该在使用 MATLAB 中的 MEX 进行编译时包含这些库。
以下是导致相同问题和错误的最小工作示例。 C代码看起来像这样,保存在MWE.c
#include "mex.h" // The mex library
#include <gsl/gsl_sf_bessel.h> // GSL function
// Define some function, in my case this is somewhat more complicated
double bessel_fun (double *x)
{
return gsl_sf_bessel_J0 (*x);
}
// MEX function needed for compiling in MATLAB
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//declare variables
mxArray *x_M, *y_M;
double *x, *y;
//associate inputs
x_M = mxDuplicateArray(prhs[0]);
//associate outputs
y_M = plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
// Access variables
x = mxGetPr(x_M);
y = mxGetPr(y_M);
// Save the result in the output variable
y[0]=bessel_fun(x);
}
然后我使用 MATLAB 在 MATLAB 中编译
mex -IC:/MinGW/include -LC:/MinGW/lib -lgsl -lgslcblas MWE.c
不是编译(如果我使用 C 代码 没有 包括任何库,这确实有效),MATLAB 返回很多错误,如下所示:
Error using mex
In file included from
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/stddef.h:7:0,
from
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/lib/gcc/x86_64-w64-mingw32/6.3.0/include/stddef.h:1,
from C:\MinGW\include/stdio.h:68,
from C:\Program Files\MATLAB\R2019a/extern/include/mex.h:38,
from C:\userpath\MWE.c:1:
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/crtdefs.h:35:19:
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'typedef'
__MINGW_EXTENSION typedef unsigned __int64 size_t;
^~~~~~~
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/crtdefs.h:45:19:
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'typedef'
__MINGW_EXTENSION typedef __int64 ssize_t;
^~~~~~~
C:/ProgramData/MATLAB/SupportPackages/R2019a/3P.instrset/mingw_w64.instrset/x86_64-w64-mingw32/include/crtdefs.h:52:9:
error: unknown type name 'size_t'
typedef size_t rsize_t;
[...]
在不同的类型名称上会出现同样的错误。
有人知道在 MATLAB 中使用 MEX 编译时如何正确包含库吗?
【问题讨论】:
-
您是如何在您的机器上获得 gsl 版本的?你自己建的吗?您是否考虑过使用二进制发行版 vs 2.2.1?
-
安装的是什么版本的MinGW?
-
我正在使用最新的
MinGW.org GCC-8.2.0-3编译C。Matlab 使用MinGW GCC 6.3 from mingw-w64.org(根据documentation 可能与32bit/64bit 版本有关吗?再说一遍,Matlab如果我不包含任何 GSL 库,编译器就可以工作。 -
这就是我问的原因。你当然需要 64 位版本。 size_t 否则未定义