将 C++ 函数暴露给 python

expose C++ function to python

C++ 代码如下所示:

struct A {
    A(int x, int y):a(x),b(y){}
    int a;
    int b;
};
std::vector<A> get_a(const A& a1, const A& a2);

并将它们暴露给 python:

BOOST_PYTHON_MODULE(Hello)
{
    using namespace boost::python;

    class_<A>("A")
        .def(init<int, int>())
        .def_readwrite("a", &A::a)
        .def_readwrite("b", &A::b);
    def("get_a", get_a);
}

将这些代码编译成 hello.pyd。并在 python 中调用 get_a 代码:

import hello
a1 = hello.A(1,2)
a2 = hello.A(3,4)
hello.get_a(a1, a2)

但这行不通:

Boost.Python.ArgumentError: Python argument types in
    hello.get_a(Boost.Python.class, Boost.Python.class)
did not match C++ signature:
    get_a(class A, class A)

我没有在 boost.python 文档中找到有关如何传递自定义对象的有用信息,该怎么做?而且我估计return类型的std::vector也不会自动处理。如何让python的列表取return的值?

要公开构造函数,需要将其传递给 class_ 而不是 def

class_<A>("A", init<int, int>())

def 用于其他构造函数,请参阅 docs

要公开 vector<A> 使用 vector_indexing_suite.

完整示例:

#include <vector>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

struct A {
    A(int x, int y) :a(x), b(y) {}
    int a;
    int b;

    bool operator==(const A& data)
    {
        return this->a == data.a && this->b == data.b;
    }
};
std::vector<A> get_a(const A& a1, const A& a2)
{
    const std::vector<A> ret = { a1,a2 };
    return ret;
}

BOOST_PYTHON_MODULE(hello) 
{
    using namespace boost::python;

    class_<std::vector<A> >("vecA")
        .def(vector_indexing_suite<std::vector<A>>())
        ;

    class_<A>("A", init<int, int>())
        .def_readwrite("a", &A::a)
        .def_readwrite("b", &A::b);
    def("get_a", get_a);
}

测试脚本:

import hello

a1 = hello.A(1,2)
a2 = hello.A(3,4)
ret = hello.get_a(a1, a2)
print "size:", len(ret)
print "values:"
for x in ret:
  print x.a, x.b 

输出:

size: 2
values:
1 2
3 4