Python綁定C++程序具體實現(xiàn)方法淺談
Python編程語言的應用范圍比較廣泛,應用方式靈活,可以很方便的幫助開發(fā)人員實現(xiàn)一些特定的功能需求。比如今天為大家介紹的有關Python綁定C++程序的相關操作,大家就可以從中了解到這一語言的應用特點。#t#
很多時候需要給C++程序提供一種使用上的靈活性,腳本語言在這里就變得很重要了。采用Boost.Python為C++程序加一層shell,比較簡單、簡潔,對原有的C++代碼也沒有侵入性。今天試了一下,感覺不錯,可以把它集成在現(xiàn)在正在做的項目中。
為Python綁定C++程序過程基本上如下:
(1)為C++類編寫一個Boost.Python wrapper
(2)編譯成so
(3)可以在python中調用了
針對David Abrahams的例子,偶的源文件如下:
Python綁定C++程序例1:hello world 函數(shù)
(1)hello.cpp
- #include < stdexcept>
- 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 < boost/python.hpp>
- 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 < boost/python.hpp>
- #include < iostream>
- using namespace std;
- using namespace boost::python;
- class World
- {
- public:
- void set(std::string msg) { this->msgmsg = msg; }
- void greet()
- {
- cout < < this->msg < < endl;
- }
- string msg;
- };
- 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()
以上就是對Python綁定C++程序的相關方法的介紹。