I was following this tutorial from boost.python
to create a shared library. Here's a simple code defining the methods that I want to expose to python.
#include <boost/python.hpp>
#include <iostream>
const int oneforth(int num, int bound) {
if (num < bound) {return num;}
return oneforth(num * (1/4), bound);
}
BOOST_PYTHON_MODULE(modd) //python module name
{
using namespace boost::python;
def("oneforth", oneforth); //python method
}
int main() {
std::cout << oneforth(10, 4);
return 0;
}
ai
I want to expose oneforth
function so I can use from modd import oneforth
.
I'm building the shared library *.so
using -
g++ -c -fPIC py.cpp -o py.o
g++ -shared py.so py.o
whenever I trying to import the dynamic py.so
, I get erros like undefined symbol
. What am I doing wrong? How does one create a shared library this way?
I tried to reproduce this and got two different error messages 'like undefined symbol'. I'll explain both since I'm not 100% sure which one you encountered.
this first was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /mnt/tmpfs/py.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv
the undefined symbol here is a mangled c++ name boost::python::objects::py_function_impl_base::max_arity() const
wich can be found in libboost_python39.so for example. This means you have to link your library with -lboost_python39
to make this symbol available.
the second was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define module export function (PyInit_py)
This one went away when I gave library file the module name that is mentioned in the source code modd.so
. I have never used boost_python before so I can't guarantee that this is in fact what the error means.
TL;TR
I got it working by changing the second build line to
g++ -shared -o modd.so py.o -lboost_python39