');

Python Language C扩展使用c ++和Boost

这是使用C ++和BoostC扩展的基本示例。

C ++代码

放入hello.cpp的C ++代码:

#include <boost/python/module.hpp>
#include <boost/python/list.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>

// Return a hello world string.
std::string get_hello_function()
{
   return "Hello world!";
}

// hello class that can return a list of count hello world strings.
class hello_class
{
public:

   // Taking the greeting message in the constructor.
   hello_class(std::string message) : _message(message) {}

   // Returns the message count times in a python list.
   boost::python::list as_list(int count)
   {
      boost::python::list res;
      for (int i = 0; i < count; ++i) {
         res.append(_message);
      }
      return res;
   }
   
private:
   std::string _message;
};


// Defining a python module naming it to "hello".
BOOST_PYTHON_MODULE(hello)
{
   // Here you declare what functions and classes that should be exposed on the module.

   // The get_hello_function exposed to python as a function.
   boost::python::def("get_hello", get_hello_function);

   // The hello_class exposed to python as a class.
   boost::python::class_<hello_class>("Hello", boost::python::init<std::string>())
      .def("as_list", &hello_class::as_list)
      ;   
}

要将其编译为python模块,您将需要python头文件和boost库。这个例子是在Ubuntu 12.04上使用python 3.4和gcc制作的。许多平台都支持Boost。在Ubuntu的情况下,使用以下方法安装所需的包:

sudo apt-get install gcc libboost-dev libpython3.4-dev

将源文件编译为.so文件,以后可以将其作为模块导入,前提是它位于python路径上:

gcc -shared -o hello.so -fPIC -I/usr/include/python3.4 hello.cpp -lboost_python-py34 -lboost_system -l:libpython3.4m.so

example.py文件中的python代码:

import hello

print(hello.get_hello())

h = hello.Hello("World hello!")
print(h.as_list(3))

然后python3 example.py将提供以下输出:

Hello world!
['World hello!', 'World hello!', 'World hello!']