Linking and LOADING static .lib with mex

前端 未结 1 925
误落风尘
误落风尘 2020-12-21 17:57

So, I have a MEX gateway script file that calls my C source code. I\'ve used the -L and -I commands to link my 64-bit compiled GSL libraries (.libs) to my mex executable, wh

相关标签:
1条回答
  • 2020-12-21 18:25

    In your previous post, you mentioned that you decided to compile GSL library with Visual C++, using the VS solution provided by Brian Gladman.

    Here is a step-by-step illustration on how to build a MEX-function that links against GSL libraries statically:

    1. Download GNU GSL sources (GSL v1.16)
    2. Download the matching Visual Studio project files (VS2012 for GSL v1.16)
    3. Extract the GSL tarball, say to C:\gsl-1.16
    4. Extract the VS project files on top of the sources, this will overwrite three files as well as add a folder C:\gsl-1.16\build.vc11.
    5. Open Visual Studio 2012, and load the solution: C:\gsl-1.16\build.vc11\gsl.lib.sln
    6. Change the configuration to the desired output: for me I chose platform=x64 and mode=Release
    7. First you must build the gslhdrs project first
    8. Now build the whole solution. This will create two static libraries cblas.lib and gsl.lib stored in C:\gsl-1.16\lib\x64\Release (along with corresponding PDB debugging symbols). It will also create a directory containing the final header files: C:\gsl-1.16\gsl

    Next we proceed to build a MEX-function. Take the following simple program (computes some value from a Bessel function, and return it as output):

    gsl_test.c

    #include "mex.h"
    #include <gsl/gsl_sf_bessel.h>
    
    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
        if (nrhs != 0 || nlhs > 1) mexErrMsgTxt("Wrong number of args.");
        plhs[0] = mxCreateDoubleScalar(gsl_sf_bessel_J0(5.0));
    }
    

    This is how to compile the above C code in MATLAB:

    >> mex -largeArrayDims gsl_test.c -I"C:\gsl-1.16" -L"C:\gsl-1.16\lib\x64\Release" cblas.lib gsl.lib
    

    Finally we test the MEX-file, and compare it against the value reported by MATLAB's own Bessel function:

    >> x = gsl_test()
    ans =
       -0.1776
    
    >> y = besselj(0,5)
    y =
       -0.1776
    
    >> max(x-y)    % this should be less than eps
    ans =
       8.3267e-17
    

    Note that the built MEX-function has no external DLL dependencies (other than "Visual C Runtime" which is expected, and the usual MATLAB libraries). You can verify that by using Dependency Walker if you want. So you can simply deploy the gsl_test.mexw64 file alone (assuming the users already have the corresponding VC++ runtime installed on their machines).

    0 讨论(0)
提交回复
热议问题