Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap a c++ library for python?

Tags:

c++

python

I have a library and some head files, no c++ source code, I want to use it with python. I tried py++, but gccxml report error. I tried swig, but some many "undefined symbol" errors. Are there some smart tools can do such things automatically?

like image 515
WhatisThat Avatar asked Oct 31 '25 14:10

WhatisThat


2 Answers

You could try using boost python

You'd need to create a simple wrapper dll that links to your original library, containing code similar to this (assuming you wanted to export a class called LibraryClass with 2 functions, foo & bar)

#include <librarytowrap.h>
#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(Library)
{
    class_<LibraryClass>("LibraryClass")
        .def("foo", &LibraryClass::foo)
        .def("bar", &LibraryClass::bar)
    ;
}

You might be able to use the automatic code generator to read the C++ definitions in the header files and do the hard work for you, but according to the boost python page this is no longer maintained, so I'm unsure how well it works.

like image 190
obmarg Avatar answered Nov 02 '25 05:11

obmarg


Can you not just use the python ctypes package?

See this tutorial.

like image 43
blokeley Avatar answered Nov 02 '25 05:11

blokeley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!