简体   繁体   中英

How to use class across modules with boost.python?

Say I have two modules, like this:

// A.cpp
class A{ /*... */};
BOOST_PYTHON_MODULE(A){
    boost::python::class_<A>("A")...
}

// B.cpp
#include "a.hpp"
int some_function(A a) { /* do something */ }

BOOST_PYTHON_MODULE(B){
    boost::python::def("some_function", some_function) ...
}

And now in python I'd like to:

import A
import B
a=A.A(...)
B.some_function(a)

However, it raised a Boost.Python.ArgumentError indicating that the call didn't match C++ signature.

So how can I pass an instance of a C++ class to a C++ function defined in other module with boost.python?

When exposing some_function in module B, use boost::python::make_function. According to the Boost.Python's documentation,

Creates a Python callable object which, when called from Python, converts its arguments to C++ and calls f.

this ensures that the arguments are converted to the right C++ types. So use

boost::python::def("some_function", boost::python::make_function(&some_function))

instead.

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