我在哪里放置来自Boost.Python的.so文件,以便将其作为模块导入,如何将它与Python 2和3一起使用

时间:2017-03-20 06:39:10

标签: python c++ python-3.x boost boost-python

我在名为cpp_examples的文件夹中有以下文件。

#include <boost/python.hpp>
#include <string>

const std::string hello() {
return std::string("hello, zoo");
}

BOOST_PYTHON_MODULE(zoo) {
// An established convention for using boost.python.
using namespace boost::python;
def("hello", hello);
}

我运行以下命令进行编译。

sumith@rztl516-Lenovo-G575:~/cpp_examples$ g++ zoo.cpp -I/usr/include/python2.7 -I/usr/lib/x86_64-linux-gnu/ -lboost_python  -lpython2.7 -o zoo.so -shared -fPIC

它被编译并给了我一个zoo.so文件。当我尝试导入并运行同一文件夹中的zoo.hello()时,它不会在cpp_examples文件夹之外导入

sumith@rztl516-Lenovo-G575:~/cpp_examples$ python2
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import zoo
>>> zoo.hello()
'hello, zoo'
>>> exit()

以下是cpp_examples文件夹之外的内容。

sumith@rztl516-Lenovo-G575:~$ python2
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import zoo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named zoo
>>> 

导入该文件夹的原因可能是什么?在编译的时候,我检查了python3,它并没有编译所有我在上面的命令中将-lpython2.7更改为-lpython3.4和-I / usr / include / python2.7到I / usr / include / python3.4但是它在编译时给我错误

/usr/bin/ld: cannot find -lpython3.4

如果我能得到这两个问题的答案,那将会有很大的帮助。 谢谢。

1 个答案:

答案 0 :(得分:1)

正如@Omnifarious最初在评论中所述,您应该查看sys.path中的目录,找到可以放置.so文件的位置。在找到import语句时,默认情况下Python将会显示在哪里。

当您在包含.so的目录中运行Python时,它很容易找到它,因为第一个条目sys.path实际上是当前目录。

至于链接,您通常应该提供pythonX.Y-config --ldflags为您提供的标记,如Compiling and Linking under Unix-like systems部分所述。

文档中的示例还使用Python 3.4为其提供示例输出:

$ /opt/bin/python3.4-config --ldflags
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic