利用boost::python使c/c++和python的交互更加方便了

之前本博客有介绍如何在python中调用的c的动态库

python调用c

调用起来非常的不方便( 是通过c_types)

今天发现 boost的提供了boost::python库,是python和c的交互更加简单直接。下面是hello world的例子:

Following C/C++ tradition, let's start with the "hello, world". A C++ Function:

char const* greet()
{
   return "hello, world";
}

can be exposed to Python by writing a Boost.Python wrapper:

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session:

>>> import hello_ext
>>> print hello_ext.greet()
hello, world

是直接从官网抄过来的

http://www.boost.org/doc/libs/1_59_0/libs/python/doc/tutorial/doc/html/index.html

 

版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章转载自:IT夜班车,否则按侵权处理.

    分享到:

Leave a Reply

Your email address will not be published. Required fields are marked *