python转c++代码_Python绑定C++程序具体实现方法浅谈

Python编程语言的应用范围比较广泛,应用方式灵活,可以很方便的帮助开发人员实现一些特定的功能需求。比如今天为大家介绍的有关Python绑定C++程序的相关操作,大家就可以从中了解到这一语言的应用特点。

很多时候需要给C++程序提供一种使用上的灵活性,脚本语言在这里就变得很重要了。采用Boost.Python为C++程序加一层shell,比较简单、简洁,对原有的C++代码也没有侵入性。今天试了一下,感觉不错,可以把它集成在现在正在做的项目中。

为Python绑定C++程序过程基本上如下:

(1)为C++类编写一个Boost.Python wrapper

(2)编译成so

(3)可以在python中调用了

针对David Abrahams的例子,偶的源文件如下:

Python绑定C++程序例1:hello world 函数

(1)hello.cpp

#include

char const* greet(unsigned x)

{

static char const* const msgs[] = { "hello", "Boost.Python", "world!" };

if (x>2)

throw std::range_error("greet: index out of range");

return msgs[x];

}

(2)hello_wrap.cpp

#include

using namespace boost::python;

char const* greet(unsigned x);

BOOST_PYTHON_MODULE(hello)

{

def("greet", greet, "return one of 3 parts of a greeting");

}

(3)makefile

PYTHON_INCLUDE_FLAGS= \

-I/usr/include/python2.4

LIB_FLAGS= \

-lboost_python

SOURCE= \

hello.cpp hello_wrap.cpp

all:${SOURCE}

g++ ${PYTHON_INCLUDE_FLAGS} ${SOURCE} ${LIB_FLAGS} -shared -o hello.so

clean:

rm -f hello *.o *.out *.so

(4)hello.py

import hello

for x in range(3):

print hello.greet(x)

Python绑定C++程序例2:hello world类

(1)hello_class.cpp

#include

#include

using namespace std;

using namespace boost::python;

class World

{

public:

void set(std::string msg) { this->msgmsg= msg; }

void greet()

{

cout<msg<

}

string msg;

};

BOOST_PYTHON_MODULE(hello)

{

class_w("World");

w.def("greet", &World::greet);

w.def("set", &World::set);

};

(2)makefile

PYTHON_INCLUDE_FLAGS= \

-I/usr/include/python2.4

LIB_FLAGS= \

-lboost_python

SOURCE= \

hello_class.cpp

all:${SOURCE}

g++ ${PYTHON_INCLUDE_FLAGS} ${SOURCE} ${LIB_FLAGS}

-shared -o hello.so

clean:

rm -f hello *.o *.out *.so(3)hello_class.py

import hello

planet=hello.World()

planet.set('howdy')

planet.greet()

以上就是对Python绑定C++程序的相关方法的介绍。

【责任编辑:曹凯 TEL:(010)68476606】

点赞 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值