python调用c++类内静态函数_从Ruby/Python调用C++类函数

您可以使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值