开发者

embed python in 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 this can be done (eg here) but I can't find any OS X specific information. So far I can successfully build an embedded Python (so my linker flags must be OK) and I can also build example mex files without any trouble and with the default options:

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
h开发者_JAVA百科ello

But when I try to build a mex file that embeds Python I run into a problem with 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 playing around with arch settings (I added -arch i386 it to try and keep everything 32bit - I am using the python.org 32 bit 2.5 build), and the order of the linker flags, but haven't been able to get anywhere. Can't find much online either. Does anyone have any ideas of how I can get this to build?

[EDIT: should probably add I'm on OS X 10.6.1 with MATLAB 7.8 (r2009a), Python 2.5.4 (python.org) - I've tried both gcc-4.0 and gcc-4.2 (apple)]


I think I found the answer - by including the mysterious apple linker flags:

-undefined dynamic_lookup -bundle

I was able to get it built and it seems to work OK. I'd be very interested if anyone has any references about these flags or library handling on OS X in general. Now I see them I remember being bitten by the same thing in the past - yet I'm unable to find any documentation on what they actually do and why/when they should be needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜