H2MEX : Matlab MEX Wrapper generator

H2MEX is a program that gernerates automatically the C++ source of an  Matlab interface file (MEX file) from header file (the .h file).

The Header file format is a pure C format, It’s extended with some

modifiers that allows to H2MEX to understand the exact task of a C routine.

The generated source (MEX file source) could be compiled without any

modification to create a DLL which is callable from Matlab.

H2MEX is developped by Alaa Makdissi. It’s based on the Matwrap package coded by Gary Holt

H2mex is Freeware.

You download it here H2MEX.EXE


Usage :

h2mex inputfile.h -o output.cpp [-outdir  DirectoryName]

where :

  • inputfile.h is an input header file that contains a description of the functions to be wrapped
  • output.cpp is the name of the file to be generated by h2mex
  • The optional -outdir DirectoryName indicates to h2mex to put the generated m files in the directory DirectoryName.

H2MEX Documentations

Most (if not all) of this text is copied (with permission) from the matwraper script written by Gary Holt.

It you have perl installed in your computer then you should use the matwrap package because it has more options and supports more languges than the h2mex program.

Who needs to use this program ?

suppose you have some functions defined in an .h file, like this:

float fiddle(double arg);

double tweedle(int x, char *name);

You can access these directly from MATLAB by using the following:

>>!h2mex fiddle.h -o myfuncs_wrap.c -outdir c:mymfiles

>>mex -v myfuncs_wrap.c

Then, in MATLAB, you can do the following:

y = tweedle(3, 'Hello, world');

A = fiddle([3, 4; 5, 6];

Note especially the last statement, where instead of passing a scalar as the argument, we pass a matrix. The c function fiddle() is called repeatedly on each element of the matrix and the result is returned as a 2×2 matrix.

Floats, doubles, char *, integer, unsigned, and pointers to structures may be used as arugments. Function pointers are not currently supported in any form. C++ operator definitions are not supported either.


C++ classes

You can access public member functions and simple public data members of classes. For example,

class ABC {

public: ABC(int constructor_arg);

void do_something(float number, int idx);

double x;


From MATLAB , you would access this structure like this:

ABC_ptr = ABC_new(3); % Call the constructor and return a pointer.

ABC_do_something(ABC_ptr, pi, 4); % Call the member function.

abc_x = ABC_get_x(ABC_ptr); % Get the value of a data member.

Page 1 of 4 | Next page