Mex

Aus Physik
Wechseln zu: Navigation, Suche

this is a tutorial on how to successfully compile and run a C or C++ mex file which uses a fortran routine fortroutine(int *i1, int *i2,...,double *d1, double *d2,..).


the mex file

Useful information on how to build a mex file can be found in the Matlab help (or maybe later in this Wiki). MATLAB provides its own data types which should be used in a mex file. One important rule is that int datatypes are replaced by mwSignedIndex data types (or mwSize data types, see MATLAB help) throughout your mex file. this means that somewhere in your mex file you have to define mwSignedIndex *i1 = ...;mwSignedIndex *i2 = ...; These are then passed to fortroutine. All usual C/C++ commands can be used in a mex file, especially new(C++) or malloc(C). MATLAB also provides a mcCalloc function to allocate memory, but I haven't used it yet.

A simple minded mex file is easy to compile and run. It get's tricky when you want to use a routine fortroutine(...) which has to be linked against libraries like arpack, lapack or blas. There one has again to distinguish between 32 and 64 bit machines.

In the end, the solution I found is as follows (tested only for .f90 files!)

LINUX 32 bit machines

compile fortroutine.f90 into an object file fortroutine.o using gfortran: gfortran -c fortroutine.f90

compile your C/C++ mex-file mexfile.c(pp): mex -output mexfile mexfile.cpp -llapack -lblas -larpack -lgfortran fortroutine.o

this should work on 32 bit machines

LINUX 64 bit machines

usually, the above compile command should still work (as long as your object file is also compiled on 64 bit). Running the mexfile might however produce seg faults. the reason is that gfortran uses 4 byte integers, but mex passes 8byte integers. Solve the problem in the following way:

1) recompile your .f90 file int a .o file: gfortran -c -fPIC -fdefault-integer-8 fortroutine.f90

2) in matlab, compile the mex file: mex -glnxa64 -largeArrayDims -llapack -lblas -larpack -lgfortran mexfile.c(pp) fortroutine.o

the flag -glnxa64 may be omitted (at the itp), but in my laptop I had to include it to get the mexfile running.

mexfile can now be executed in matlab