Mac 中使用 SWIG for Python 的 C++ 最小示例

Vaa*_*l88 4 macos swig

我正在尝试在 OSX 中使用 SWIG 为一些 C++ 代码编译一个 python 包装器的最小示例。

/* File : example.c */
double My_variable = 3.0;

int fact(int n) {
    if (n <= 1) return 1;
    else return n*fact(n-1);
}

int my_mod(int x, int y) {
    return (x%y);
}
Run Code Online (Sandbox Code Playgroud)

和接口文件:

/* example.i */
%module example
%{
    /* Put header files here or function declarations like below */
    extern int fact(int n);
    extern int my_mod(int x, int y);
%}

extern int fact(int n);
extern int my_mod(int x, int y);
Run Code Online (Sandbox Code Playgroud)

我运行以下命令:

swig -python -o example_wrap.c example.i 
gcc -c -arch x86_64 -fPIC example.cxx -o example.o -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7
ld -bundle -macosx_version_min 10.13 -flat_namespace -undefined suppress -o _example.so *.o
Run Code Online (Sandbox Code Playgroud)

所有这些都正确创建了 _example.so、example_wrap.c、example.o 和 example.py。然后我运行python2.7

import example
Run Code Online (Sandbox Code Playgroud)

我得到

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "example.py", line 17, in <module>
    _example = swig_import_helper()
  File "example.py", line 16, in swig_import_helper
    return importlib.import_module('_example')
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: dynamic module does not define init function (init_example)
Run Code Online (Sandbox Code Playgroud)

任何想法?

Vaa*_*l88 5

我解决了它:

Swig -python example.i
Gcc -fPIC -c example.c
gcc -fPIC -c example_wrap.c -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/
gcc -dynamiclib -o _example.so *.o -L/usr/lib/ -lpython2.7 -flat_namespace
Run Code Online (Sandbox Code Playgroud)

这里重要的是 -flat_namespace。但不知道为什么。