2016-03-04 84 views
0

的C++代码如下:暴露C++函数到Python

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:

​​

建立这些代码放到一个hello.pyd。并呼吁get_a在Python代码:

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的文档了解如何通过自定义的对象,如何去做这个?我猜std :: vector的返回类型也不会自动处理。如何让python的列表获取返回值?

回答

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