问题
Let's say I have two modules in a python project that are written in C++ and exposed with boost::python.
mod1.hpp
#ifndef MOD1_HPP
#define MOD1_HPP
#include <boost/python.hpp>
int square(int x);
#endif
mod1.cpp
#include "mod1.hpp"
using namespace boost::python;
int square(int x)
{
return x*x;
}
BOOST_PYTHON_MODULE (mod1)
{
def("square",&square);
}
mod2.hpp
#ifndef MOD2_HPP
#define MOD2_HPP
#include <iostream>
#include <boost/python.hpp>
#include "mod1.hpp"
int myfunc(int x);
#endif
mod2.cpp
#include "mod2.hpp"
using namespace boost::python;
int myfunc(int x)
{
int y = square(x);
std::cout << y << std::endl;
}
BOOST_PYTHON_MODULE (mod2)
{
def("myfunc",&myfunc);
}
As you can see, mod2 is using a function defined in mod1. Compiled without the boost::python wrapper and with a main function, it works perfectly fine.
Now the compile script
setup.py
#!/usr/bin/python2
from setuptools import setup, Extension
mod1 = Extension('mod1',
sources = ['mod1.cpp'],
libraries = ['boost_python'])
mod2 = Extension('mod2',
sources = ['mod2.cpp'],
libraries = ['boost_python'])
setup(name='foo',
version='0.0',
description='',
ext_modules=[mod1,mod2],
install_requires=['distribute'])
it compiles fine. Then I move to build/lib.linux-i686-2.7
and launch python2
>>> import mod1
>>> import mod2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: ./mod2.so: undefined symbol: _Z6squarei
>>>
Obviously there's a problem with mod2 not finding mod1. How can I fix that ? How can I define several C modules in a python project and allow them to use each others ?
回答1:
Since mod1 is a Python extension, the clean approach would be to use it just like any other Python module:
object mod1 = import("mod1");
object square = mod1.attr("square");
int y = extract<int>(square(x));
来源:https://stackoverflow.com/questions/8443652/dependencies-between-compiled-modules-in-python