将C ++函数暴露给python

时间:2016-03-04 03:13:36

标签: boost-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 doc中找到有关如何传递自定义对象的有用信息,该怎么做?我想返回类型std :: vector也不会自动处理。如何让python的列表获取返回值?

1 个答案:

答案 0 :(得分:0)

要公开构造函数,需要将其传递给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