织梦CMS - 轻松建站从此开始!

罗索

python绑定c++程序

jackyhwei 发布于 2010-01-24 01:13 点击:次 
很多时候需要给c++程序提供一种使用上的灵活性,脚本语言在这里就变得很重要了。采用Boost.Python为c++程序加一层shell,比较简单、简洁,对原有的c++代码也没有侵入性。
TAG:

很多时候需要给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

  1. #include <stdexcept> 
  2. char const* greet(unsigned x) 
  3.    static char constconst msgs[] = { "hello""Boost.Python""world!" }; 
  4.  
  5.    if (x > 2) 
  6.        throw std::range_error("greet: index out of range"); 
  7.  
  8.    return msgs[x]; 

(2)hello_wrap.cpp

  1. #include <boost/python.hpp> 
  2.  
  3. using namespace boost::python; 
  4.  
  5. char const* greet(unsigned x); 
  6.  
  7. BOOST_PYTHON_MODULE(hello) 
  8.     def("greet", greet, "return one of 3 parts of a greeting"); 

(3)makefile

  1. PYTHON_INCLUDE_FLAGS = \ 
  2.     -I/usr/include/python2.4 
  3.  
  4. LIB_FLAGS = \ 
  5.     -lboost_python 
  6.  
  7. SOURCE = \ 
  8.     hello.cpp hello_wrap.cpp 
  9.  
  10. all:${SOURCE} 
  11.     g++ ${PYTHON_INCLUDE_FLAGS} ${SOURCE} ${LIB_FLAGS} -shared -o hello.so 
  12. clean: 
  13.     rm -f hello *.o *.out *.so 

(4)hello.py

  1. import hello 
  2. for x in range(3): 
  3.     print hello.greet(x) 

例2:hello world类
(1)hello_class.cpp

  1. #include <boost/python.hpp> 
  2. #include <iostream> 
  3. using namespace std; 
  4. using namespace boost::python; 
  5.  
  6. class World 
  7. public
  8.  
  9.     void set(std::string msg) { this->msg = msg; } 
  10.     
  11.     void greet() 
  12.     { 
  13.         cout << this->msg << endl; 
  14.      } 
  15.      
  16.     string msg; 
  17. }; 
  18.  
  19. BOOST_PYTHON_MODULE(hello) 
  20.     class_<World> w("World"); 
  21.     w.def("greet", &World::greet); 
  22.     w.def("set", &World::set); 
  23. }; 

(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

  1. import hello 
  2. planet = hello.World() 
  3. planet.set('howdy'
  4. planet.greet() 

更复杂的调用见上面提到的David Abrahams的文章。http://www.cnblogs.com/xiaotie/archive/2006/02/22/335633.html

(David Abrahams)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201001/8370.html]
本文出处:boost-consulting.com 作者:David Abrahams
顶一下
(1)
100%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容