在制作boost.python helloword演示时不安全地使用相对rpath libboost.dylib?

时间:2015-10-22 13:05:00

标签: python c++ macos boost

最近,我正在学习boost C ++库。我想用python来调用现有的C ++项目。我使用brew install boost在OSX 10.11下安装了boost。我的python版本2.7。

我做了一个hello.c:

char const* greet()
{
    return "hello, world";
}

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello)
{
    using namespace boost::python;
    def("greet", greet);
}

和Makefile:

PYTHON_VERSION = 2.7
PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)

# location of the Boost Python include files and library
#  
BOOST_INC = /usr/local/include
BOOST_LIB = /usr/local/lib
#   
# compile mesh classes
TARGET = hello

$(TARGET).so: $(TARGET).o
    g++ -shared -Wl $(TARGET).o -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so

$(TARGET).o: $(TARGET).c
    g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).c

然而,在我运行make并获得hello.so之后。我运行python代码时遇到以下错误:

import hello
print hello.greet()

错误:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    import hello
ImportError: dlopen(/Users/einverne/boost_test/hello.so, 2): Library not loaded: libboost_python.dylib
  Referenced from: /Users/einverne/boost_test/hello.so
  Reason: unsafe use of relative rpath libboost_python.dylib in /Users/einverne/boost_test/hello.so with restricted binary

2 个答案:

答案 0 :(得分:16)

将此link作为参考。

要解决我的问题,请使用otool -L hello.so

hello.so:
    hello.so (compatibility version 0.0.0, current version 0.0.0)
    libboost_python.dylib (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.10)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.1.1)

你可以看到libboost_python.dylib没有指向真正存在的路径。

所以使用这个命令:

install_name_tool -change libboost_python.dylib /usr/local/lib/libboost_python.dylib hello.so 

再次运行otool -L hello.so

hello.so:
    hello.so (compatibility version 0.0.0, current version 0.0.0)
    /usr/local/lib/libboost_python.dylib (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.10)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.1.1)

最后运行python test.py,我得到了结果。

答案 1 :(得分:0)

建议在MacOS上更改Boost动态库,而不是更改与其链接的可执行文件或其他动态库。在包含bash库的目录中运行下面给出的libboost_XXX.dylib脚本:

#!/bin/bash

# Modify the absolute dylib paths baked into the libraries
for i in *.dylib
do
    FULLPATH=`pwd`/$i
    install_name_tool -id $FULLPATH $i
    echo -change $i $FULLPATH
    done > changes
for i in *.dylib
do
    install_name_tool `cat changes` $i
done
rm changes

构建Boost库后,您只需执行此操作一次。不需要乱用链接它们的可执行文件。