美文网首页
初探pybind11——Python调用C++函数

初探pybind11——Python调用C++函数

作者: 碳负离子 | 来源:发表于2022-01-10 21:45 被阅读0次

    本文使用Anaconda环境进行演示,python版本为3.8,若读者不使用Anaconda,需自行配置环境。

    Pybind11是一个纯头文件库,用于将C++函数封装出Python接口。该库可以很方便地使用conda进行安装,执行命令conda install pybind11 pytest。完成安装后,我们开始编写第一个程序,命名为hello.cpp

    // hello.cpp
    #include <pybind11/pybind11.h>
    #include <iostream>
    namespace py = pybind11;
    using namespace std;
    
    void say_hello(const char* name)
    {
        cout << "Hello, " << name << "! This is a message from C++ library!" << endl;
    }
    
    PYBIND11_MODULE(hello, m)
    {
        m.def("say_hello", &say_hello, "Print hello to the name.");
    }
    

    上面的cpp文件中,say_hello为程序函数,PYBIND11_MODULE为包装函数,此二者在实际应用中一般会分别存放在不同的文件中,但在本例中为演示需要,我将他们放在了同一个文件中。

    PYBIND11_MODULE是一个宏定义,其功能是创建一个函数,这个函数会在Python执行import语句时被调用,其接受两个参数,第一个参数为模块名称,这里我们直接将hello填入,稍候可以在Python中使用import hello导入该模块;第二个参数m是创建Python关联代码的主接口,其类型为py::module_module_::def()用于生成能够将say_hello函数暴露给Python的代码,其第一个参数为字符串,将会成为Python中调用的函数名;第二个参数是C++函数的引用;第三个参数是说明字符串,在Python中可以使用help(say_hello)查看。

    现在,我们可以着手编译这个库了,这里我使用g++进行编译,通过-shared参数将其编译为共享库,在Linux和MacOS上的编译命令稍有不同:

    • Linux
    g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) hello.cpp -o hello$(python3-config --extension-suffix)
    
    • MacOS
    g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) hello.cpp -o hello$(python3-config --extension-suffix) -undefined dynamic_lookup
    

    在我的系统中,会生成一个名为hello.cpython-38-darwin.so的文件,这就是编译产生的共享库文件。现在,在当前目录进入python解释器,即可导入包并运行函数:

    $ python
    Python 3.8.12 (default, Oct 12 2021, 06:23:56) 
    [Clang 10.0.0 ] :: Anaconda, Inc. on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import hello
    >>> hello.say_hello("Tom")
    Hello, Tom! This is a message from C++ library!
    

    除了手动编译外,还可以使用cmake工具进行跨平台编译配置,在当前目录下新建一个CMakeLists.txt文件,然后写入下面的命令:

    cmake_minimum_required(VERSION 3.4...3.18)
    project(hello)
    find_package(Python COMPONENTS Interpreter Development REQUIRED)
    find_package(pybind11 REQUIRED)
    pybind11_add_module(hello hello.cpp)
    

    其中,find_package函数会自动找到正确的依赖包,pybind11_add_module函数添加了一个名为hello的模块。

    保存退出后,执行cmake . && make命令,即可看到编译产生的共享库文件。


    使用py::arg参数可以将变量名也暴露给python,同时,若有需要,还可以设置参数默认值:

    PYBIND11_MODULE(hello, m)
    {
        m.def("say_hello", &say_hello, "Print hello to the name.", py::arg("name")="Jack");
    }
    

    Python运行效果:

    >>> import hello
    >>> hello.say_hello()
    Hello, Jack! This is a message from C++ library!
    >>> hello.say_hello("Nic")
    Hello, Nic! This is a message from C++ library!
    >>> hello.say_hello(name="George")
    Hello, George! This is a message from C++ library!
    >>> help(hello.say_hello)
    Help on built-in function say_hello in module hello:
    
    say_hello(...) method of builtins.PyCapsule instance
        say_hello(name: str = 'Jack') -> None
        
        Print hello to the name.
    (END)
    

    py::arg参数还有一种简化写法,通过引入名称空间pybind11::literals,可以使用_a后缀来替代py::arg,例如,上面的一条m.def函数可以写成:

    using namespace pybind11::literals;
    PYBIND11_MODULE(hello, m)
    {
        m.def("say_hello", &say_hello, "name"_a="Jack");
    }
    

    除了包装函数外,通过使用module_::attr函数可以将C++中的变量暴露给Python,例如下面的C++程序:

    // hello.cpp
    #include <pybind11/pybind11.h>
    #include <iostream>
    namespace py = pybind11;
    using namespace std;
    using namespace pybind11::literals;
    
    const char* where = "This is a message from C++ library!";
    const char* cst = "This is an auto cast string by pybind11.";
    
    void say_hello(const char* name)
    {
        cout << "Hello, " << name << "!" << endl;
    }
    
    PYBIND11_MODULE(hello, m)
    {
        m.def("say_hello", &say_hello, "name"_a="Jack");
        m.attr("where") = where;
        m.attr("cast") = py::cast(cst);
    }
    

    Python中运行效果:

    >>> import hello
    >>> hello.say_hello("Tom")
    Hello, Tom!
    >>> print(hello.where)
    This is a message from C++ library!
    >>> print(hello.cast)
    This is an auto cast string by pybind11.
    >>> type(hello.cast)
    <class 'str'>
    

    相关文章

      网友评论

          本文标题:初探pybind11——Python调用C++函数

          本文链接:https://www.haomeiwen.com/subject/pbsvcrtx.html