Python – Embed Python in a Matlab MEX file on OS X

Embed Python in a Matlab MEX file on OS X… here is a solution to the problem.

Embed Python in a Matlab MEX file on OS X

I’m trying to embed Python into a MATLAB mex function on OS X. I’ve seen references that can do this (e.g. here ), but I can’t find any OS X specific information. So far, I’ve been able to successfully build an embedded Python (so my linker flag has to be fine), and I can also build the sample mex file without any problem with the default option:

jm-g26b101:mex robince$ cat pytestnomex.c
#include <Python/Python.h>

int main() {
  Py_Initialize();
  PyRun_SimpleString("print 'hello'"); 
  Py_Finalize();
  return 0;
}
jm-g26b101:mex robince$ gcc -arch i386 pytestnomex.c -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -L/Library/Frameworks/Python.framework/Versions/ 2.5/lib/python2.5/config -ldl -lpython2.5
jm-g26b101:mex robince$ ./a.out
hello

But when I tried to build a mex file embedded in Python, I ran into the problem of undefined symbol main. Here is my mex function:

#include <Python.h>
#include <mex.h>

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])
{
    mexPrintf("hello1\n");
    Py_Initialize();
    PyRun_SimpleString("print 'hello from python'");
    Py_Finalize();
}

Here are the mex compilation steps:

jm-g26b101:mex robince$ gcc -c  -I/Applications/MATLAB_R2009a.app/extern/include -I/Applications/MATLAB_R2009a.app/simulink/include -DMATLAB_MEX_FILE  -arch i386 -I/ Library/Frameworks/Python.framework/Versions/2.5/include/python2.5  -DMX_COMPAT_32 -O2 -DNDEBUG  "pytest.c"
jm-g26b101:mex robince$ gcc -O  -arch i386 -L/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -ldl -lpython2.5 -o  "pytest.mexmaci"  pytest.o  -L/Applications/ MATLAB_R2009a.app/bin/maci -lmx -lmex -lmat -lstdc++
Undefined symbols:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

I’ve tried using the arch setup (I added -arch i386 to try to keep everything at 32-bit – I’m using the python.org 32-bit 2.5 version), and the order of the linker flags, but haven’t gotten anywhere yet. There are not many found online. Does anyone know how I build it?

[EDIT: Probably should add that I’m using MATLAB 7.8 (r2009a), Python 2.5.4 (python.org) on OS X 10.6.1 – I’ve tried gcc-4.0 and gcc-4.2 (apple)].

Solution

I

think I found the answer – by including the mysterious Apple Linker logo:

-undefined dynamic_lookup -bundle

I was able to build it and it seems to work fine. I would be very interested if anyone had any references to these flags or library handling on OS X. Now that I see them, I remember being bitten by the same thing in the past – but I can’t find any documentation on what they actually do and why/when they need them.

Related Problems and Solutions