3

我正在尝试将 Python 嵌入到 OS X 上的 MATLAB mex 函数中。我已经看到可以做到这一点的参考资料(例如这里),但我找不到任何 OS X 特定信息。到目前为止,我可以成功构建一个嵌入式 Python(所以我的链接器标志必须没问题),我还可以毫无问题地使用默认选项构建示例 mex 文件:

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

但是当我尝试构建一个嵌入 Python 的 mex 文件时,我遇到了未定义符号 main 的问题。这是我的 mex 函数:

#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();
}

以下是 mex 编译步骤:

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

我尝试过使用 arch 设置(我添加了 -arch i386 以尝试将所有内容保持为 32 位 - 我正在使用 python.org 32 位 2.5 构建)和链接器标志的顺序,但还没有去任何地方。网上也找不到很多。有人对我如何构建它有任何想法吗?

[编辑:可能应该添加我在 OS X 10.6.1 和 MATLAB 7.8 (r2009a)、Python 2.5.4 (python.org) - 我已经尝试过 gcc-4.0 和 gcc-4.2 (apple)]

4

1 回答 1

4

我想我找到了答案——通过包含神秘的苹果链接器标志:

-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.

于 2009-11-09T13:48:29.580 回答