【问题标题】:swig-generated code links to wrong python installationswig 生成的代码链接到错误的 python 安装
【发布时间】:2014-03-26 00:51:53
【问题描述】:

我有以下问题,

我正在使用 swig 构建一个 python 模块来包装 C 代码。 我已经使用 MacPorts 安装了 python、gcc(45)、..。

这是重现问题的最小设置:

两个文件:

test.i:

%module test
double sum(double a, double b);

test.c:

double sum(double a, double b){return a+b;}

我跑

$ swig -python  -I. test.i
$ gcc -fPIC -I/opt/local/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c test_wrap.c
$ gcc    -c -o test.o test.c
$ gcc -shared -I/opt/local/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -lpython -dynamiclib -fPIC -o _test.so test.o test_wrap.o

当我运行 python(MacPorts 之一:/opt/local/bin/python2.7)并尝试通过import test 导入模块时,代码崩溃并出现与上述完全相同的问题。

使用 otool 检查文件 _test.so 会得到以下结果:

$ otool -L _test.so
_test.so:
   _test.so (compatibility version 0.0.0, current version 0.0.0)
   /System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.2)
   /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1669.0.0)
   /opt/local/lib/libgcc/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
   /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)

我发现在 swig 生成的文件 test.py 中包含 #include <Python.h> 行。但是 /System/Library/... 中有一个 Python.h,/opt/local/... 中有一个 我的猜测是这里发生了错误。但是如何使编译器/链接器指向正确的?

非常感谢您的帮助!! 托马斯

【问题讨论】:

  • 我找到了答案,而不是 -I/opt/local/Library... -lpython ,使用 -F/opt/local/Library/Frameworks/ -framework python

标签: python macos gcc swig macports


【解决方案1】:

我没有 mac,但是在使用 swig(swig docdistutil doc)时,通过使用 distutils 在 Linux 和 Windows 上处理多个 Python 版本,我得到了很好的结果。下面显示了一个 setup.py 的最小示例:

from distutils.core import setup,Extension
ext = Extension('_test',sources=['test.c,test.i'])
setup(name='test',ext_modules=[ext],py_modules=["test"])

Distutils 绑定到调用 python 版本并且知道 swig。但是,重要的是通过以下方式编译:

python setup.py build_ext
python setup.py build_py

而不是直接调用 build。

【讨论】:

    猜你喜欢
    • 2010-12-10
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多