简体   繁体   中英

Extending C++ functions to Python using Boost Python

I am trying to wrap up two c++ files to be used in Python. I am using the boost python library. The files appear to compile correctly, but importing the modules results in a "ImportError: undefined symbol" error.

This issue has something to do with boost not correctly finding my dependent c++ files, but I am not clear as to how to add them.

Python Version: 2.7.12 Boost Version: 1.58 OS: Ubuntu 16.04

My code structure is as follows:

hellomodule.cpp

#include <iostream>
#include <cstdint>
#include "test.h"

using namespace std;

void say_hello(const char* name) {
    cout << "Hello " <<  name << "!\n";
    run_test();
}

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(hello)
{
    def("say_hello", say_hello);
}

test.cpp

#include "test.h"
using namespace std;

void run_test(void){
    cout << "Sup";
}

setup.py

#!/usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension

module1 = Extension("hello",
                    sources = ["hellomodule.cpp", "test.cpp"],
                    libraries = ["boost_python"],
                    extra_compile_args=['-std=c++11'])

setup(name="PackageName",
    ext_modules=[module1])

From the command line I run "python setup.py build" which creates my hello.so file. When I try to import "hello" I get "ImportError: ./hello.so: undefined symbol: _Z8run_testv"

If someone could please point me in the right direction, it would be greatly appreciated.

It seems like you may have some stale files around. I was able to reproduce the issue by omitting test.cpp from sources in setup.py . In this case it builds just fine, but as you observed, does not import. It might be that Python is finding a version of hello.so that you built previously before adding test.cpp in.

I'd suggest removing the build dir and any copies of hello.so that might be lying around and trying to run the build from scratch again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM