您可以使用cython或Boost.Python从python调用本机代码。因为您使用的是c++,所以我建议您研究一下Boost.Python,它为python包装c++类提供了一种非常自然的方式。在
作为一个示例(与您提供的内容相近),考虑下面的类定义class Bar
{
private:
int value;
public:
Bar() : value(42){ }
//Functions to expose to Python:
int getValue() const { return value; }
void setValue(int newValue) { value = newValue; }
};
class Foo
{
private:
//Integer Vector:
std::vector fooVector;
Bar bar;
public:
//Functions to expose to Python:
void pushBack(const int& newInt) { fooVector.push_back(newInt); }
int getInt(const int& element) { return fooVector.at(element); }
Bar& getBar() { return bar; }
};
double compute() { return 18.3; }
可以使用Boost.Python在
^{pr2}$
这段代码可以编译成一个静态库MyLibrary.pyd,并按如下方式使用import MyLibrary
foo = MyLibrary.Foo()
foo.pushBack(10);
foo.pushBack(20);
foo.pushBack(30);
print(foo.getInt(0)) # 10
print(foo.getInt(1)) # 20
print(foo.getInt(2)) # 30
bar = foo.getBar()
print(bar.getValue()) # 42
bar.setValue(17)
print(foo.getBar().getValue()) #17
print(MyLibrary.compute()) # 18.3