c - 将 GSL 库链接到 Matlab MEX 时如何修复“未知类型名称”错误
问题描述
我目前正在尝试优化我在 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 中使用
mex -IC:/MinGW/include -LC:/MinGW/lib -lgsl -lgslcblas MWE.c
MATLAB 没有编译(如果我使用不包含任何库的 C 代码,它确实有效),而是返回很多错误,如下所示:
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 编译时如何正确包含库?
解决方案
明白了。请您尝试以下方法:
mex -U__MINGW_EXTENSION -IC:/MinGW/include -LC:/MinGW/lib -lgsl -lgslcblas MWE.c
推荐阅读
- c++ - 如何防止 clang-format 在#define 列表之前添加换行符
- python - 如何检查是否存在具有所有特征 nan 值的行/样本?
- python - 我需要使用 selenium-chromedriver 在电报机器人中发送复制的文本
- c# - C# .net core 3.1 WPF 无异常关闭
- python - 递归 - 具有 N 个子串限制的最长公共子序列
- .net - DynamoDB 的新手。有没有更方便的添加/放置项目的方法?
- angularjs - 为什么AngularJS中突然出现这个错误?
- javascript - 多功能按钮
- python - Pandas 更新 dataframe1 中的 A 列,其中 dataframe1 column2 与 dataframe2 列匹配
- python - 如何解决这个 IndexError: list index out of range