python绑定c++程序

python绑定c++程序 - xiaotie - 博客园

python绑定c++程序

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



我主要参照David Abrahams的"Building Hybrid Systems with Boost.Python"(http://www.boost-consulting.com/writing/bpl.html)一文,该文中对编译 过程说的较少,偶就略做补充,为新手节省点时间(偶也是python新手)。



为c++类加python shell过程基本上如下:

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

(2)编译成so

(3)可以在python中调用了



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



例1:hello world 函数

(1)hello.cpp

#include<stdexcept>

charconstgreet(unsigned x)

{

staticcharconst
constmsgs[]={"hello","Boost.Python","world!"};



if(x>2)

throwstd::range_error("greet: index out of range");



returnmsgs[x];

}

(2)hello_wrap.cpp

#include<boost/python.hpp>



usingnamespaceboost::python;



charconstgreet(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

forxinrange(3):

print hello.greet(x)

例2:hello world类

(1)hello_class.cpp

#include<boost/python.hpp>

#include
<iostream>

usingnamespacestd;

usingnamespaceboost::python;



classWorld

{

public:



voidset(std::stringmsg) {this->msg=msg; }



voidgreet()

{

cout
<<this->msg<<endl;

}



stringmsg;

};



BOOST_PYTHON_MODULE(hello)

{

class_
<World>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()



更复杂的调用见上面提到的David Abrahams的文章。原文链接: https://www.cnblogs.com/lexus/archive/2012/12/14/2818730.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/72485

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午3:26
下一篇 2023年2月9日 下午3:26

相关推荐