c++和python的互相调用

前提

因项目需求,需要在C++中调用python,对这方面的一些工具做个简单的介绍。

ctypes

ctypes 是 Python 的外部函数库。它提供了与 C 兼容的数据类型,并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进行封装。
上面是ctypes官方文档给出的介绍,通俗理解来说:ctypes可以加载动态链接库,然后以此调用动态链接库中的函数。也就是说,如果我们有一个.c文件,我们可以将它编译成库,然后在python代码里面使用ctypes加载调用它。
相关代码如下:

  1. 创建一个main.c文件,包括三个函数,等会我们要通过调用动态链接库的方式在python中调用这三个函数。
// main.c
#include <stdio.h>
#include <stdlib.h>

int add(int a, int b) {
    return a + b;
}

int sum(int *a, int num){
    int sum = 0;
    for(int i=0; i<num; i++){
        sum += a[i];
    }
    return sum;
}
  1. main.c编译为动态链接库mainlib.dll
gcc -shared -o mainlib.dll main.c
  1. 现在我们的文件夹下便会多出一个mainlib.dll库文件,接下来我们在python中调用并且使用它。
# demo.py
import ctypes
from ctypes import *
mainlib = ctypes.CDLL('test/mainlib.dll')

a = ctypes.c_int(1)
b = ctypes.c_int(2) 
print(mainlib.add(a,b))

# 要想传入int类型的数组,就必须按照下面的方式先进行定义
int_array = (c_int * 3)(1, 2, 3)
num = ctypes.c_int(3)
print(mainlib.sum(int_array, 3))

总结: ctypes可以应用到在python中调用c函数,也就是python调用C,也就是扩展python。

pybind11

pybind11之前我使用过,当时的场景是:有一个深度学习算子是用c++和cuda写的,要把它接入到pytorch中,相当于是python中调用c++。当时的解决方案是:使用pybind11这个工具将这个算子封装成动态库文件,然后在python端进行加载运行。

在这里,我可以很明确的告诉大家:pybind11可以使我们在python中调用C++(这是pybind11的主要目的和应用),也可以使我们在C++中调用python。 下面给出两个示例。

在python中调用C++

  1. 安装pybind11
    这里我建议使用conda install 的方式安装pybind11,否在后面在C++中会找不到pybind的头文件等。
conda install pybind11
  1. 创建main.cpp
#include <pybind11/pybind11.h>

namespace py = pybind11;

int add(int i, int j){
    return i+j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring

    m.def("add", &add, "A function that adds two numbers");
}

可以看到,在main.c中定义了一个add函数。后面几行添加了pybind接口的代码。

  1. 生成动态链接库
    生成动态链接库这一部分,很多教程中使用的都是一个setup.py,这里我使用从官网得到的命令行生成.so文件。
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) main.cpp -o example$(python3-config --extension-suffix)

运行完这条指令后,可以看到文件夹中多了一个以example开头的.so文件。

  1. 在python中调用该动态链接库
import example
example.add(1,2)  # 3

以上就是使用pybind11在python中调用c++的全流程。

在C++中调用python

这一部分互联网上资源很少,我没有找到一个完整的demo,最后从pybind11的官网 找到了一些demo,这里进行展示。

  1. 准备c++环境
    因为我是使用cmake编译代码,所以第一步要找到pybind11的头文件,也就是确保CmakeLists.txt文件正确。下面是我的cmake文件。
cmake_minimum_required(VERSION 3.16)
project(main)

find_package(pybind11 REQUIRED)  # 寻找pybind11

add_executable(main main.cpp)
target_link_libraries(main pybind11::embed)
  1. demo
#include <pybind11/embed.h> // 注意,这里的头文件和上一个不一样
#include <iostream>
namespace py = pybind11;


int main(){
    py::scoped_interpreter guard{};  // 激活python解释器

    py::print("hello, world!");  // 使用python api

     py::exec(R"(
        kwargs = dict(name="World", number=42)
        message = "Hello, {name}! The answer is {number}".format(**kwargs)
        print(message)
    )");  // 使用exec在c++中运行python代码

    // 在c++中导入python的模块
    py::module_ sys = py::module_::import("sys");
    py::print(sys.attr("path"));  // 为了简单起见,现在的工作目录已经被添加到了`sys.path`里面。
    
    /* 1. 创建calc.py
    *
    *"""calc.py located in the working directory"""
    *   def add(i, j):
    *       return i + j
    */
    
    // 2. import calc module
    py::module_ calc = py::module_::import("calc");
    // 3. call calc module's method
    py::object result = calc.attr("add")(1,2);
    int n = result.cast<int>();
    std::cout<<"n = "<<n<<std::endl;

    return 0;
}

Cython

这里先强调一点:Cython和CPython是完全不同的两个东西以及这篇文章
Cython是一门结合了C和Python的编程语言(Cython是python的超集),接下来我们给出Cython几种不同的作用,但是无论如何,在linux下Cython最后都会生成一个.so文件。

加快python速度

我们有一个python写的斐波那契数列,但是运行速度太慢,因为Cython中有C语言的特性,所以我们可以使用Cython语言重写斐波那契数列,然后编译为动态链接库,然后在python代码中使用。
代码如下:
1.斐波那契数列原始的python代码:

## fib.py
def fib(n):
    a, b = 0.0, 1.0
    for i in range(n):
        a, b = a + b, a
    return a

用Cython重写的斐波那契数列,文件后缀名为.pyx:

## fib.pyx
def fib(int n):
    cdef int i
    cdef double a = 0.0, b = 1.0
    for i in range(n):
        a, b = a + b, a
    return a

  1. 编译fib.pyx文件为动态链接库.so
    这里有两种编译方式,一种是使用setup.py自动进行编译,一种是手动进行编译。
    • setup.py文件

      from distutils.core import setup
      from Cython.Build import cythonize
      
      
      setup(ext_modules = cythonize("fib.pyx"))
      

      然后在命令行运行python setup.py build_ext --inplace 便会在同级目录下生成一个以fib开头的动态链接库以及一个fib.c文件,这个fib.c文件就是fib.pyx完全转为c代码后结果。

    • 手动编译

      • 第一步:在命令行运行cython fib.pyx,会生成fib.c
      • 使用gcc对fib.c编译生成动态链接库: gcc -fPIC -shared -I ~/miniconda3/include/python3.11/ fib.c -o fib.so。注意这里python include的路径需要你自己更换为自己环境的路径。

这样在第2步,我们就生成了动态链接库.so文件。

  1. 在python代码中使用这个动态链接库

    import fib
    
    print(fib.fib(100))
    

以上就是Cython工作的大体流程。这里要注意的是:我的介绍只是一点点入门知识,Cython还是很博大精深的。

在C中调用python代码

上面我们已经说过,Cython是python的超集,所以如果我们有一个python脚本或者模块,想要在C语言环境中调用它,那么可以使用cython对这个py文件进行编译生成动态链接库,然后在C语言中调用它即可。

注:这一种方式博主没有亲自测试过

调用Python的原生C API

这是最暴力的一种方法,我们知道,python这个语言也有C的API,所以我们可以直接在C语言代码中使用这些API来调用python模块,下面是一个简单的示例。

  1. 我们拥有的my_modules.py文件

    # # my_modules.py
    def add(a, b):
        print(a + b)
        return a + b
    
    def helloworld(s):
        print("hello " + s)
    
    
    class A:
        def __init__(self, a, b) -> None:
            self.first = a
            self.second = b
    
        def add(self):
            print(self.first+self.second)
            return "hello world"
    

    可以看到,有两个函数(一个做求和,一个输出"hello world")和一个类。

  2. 构建C++的环境
    我是使用cmake进行编译程序的,所以要配置好CMakeLists.txt,配置如下:

cmake_minimum_required(VERSION 3.16)
project(CallPython)

find_package (Python COMPONENTS Interpreter Development)  # 找到python解释器
message(STATUS "Python_VERSION: ${Python_INCLUDE_DIRS}")
message(STATUS "python_LIBRARIES: ${Python_LIBRARIES}")
# message(STATUS "python_Interpreter: ${ython_LIBRARIES}")
# message(STATUS "python_LIBRARIES: ${ython_LIBRARIES}")
include_directories(
    ${Python_INCLUDE_DIRS} 
    )
# 生成目标文件
add_executable(call_python call_python.cpp)
# 链接库
target_link_libraries(call_python ${Python_LIBRARIES})
  1. 创建call_python.cpp文件,文件内容如下:
#include <iostream>
#include <Python.h>  // 必须要有这个头文件,在cmake中进行配置也是为了找到这个头文件

int main(int argc, char** argv){
    // 运行Python解释器
    Py_Initialize();
    
    // 添加.py的路径
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/wjq/workspace/test1')"); // py文件的父目录
	
    /**************************
    ********* add函数 **********
    **************************/
    
    // 导入模块
    PyObject* pModule = PyImport_ImportModule("my_modules"); 
    // 导入要运行的函数
    PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
    // 构造传入参数    
    PyObject* args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, Py_BuildValue("i", 1));
    PyTuple_SetItem(args, 1, Py_BuildValue("i", 10));
    // 运行函数,并获取返回值
    PyObject* pRet = PyObject_CallObject(pFunc, args); 
    if (pRet)
    {
        long result = PyLong_AsLong(pRet); // 将返回值转换成long型  
        std::cout << "result:" << result << std::endl ;
    }  
	
    /**************************
    ****** helloworld函数 *****
    **************************/
    
	// 导入函数
    pFunc = PyObject_GetAttrString(pModule, "helloworld");
    // 构造传入参数
    PyObject* str = Py_BuildValue("(s)", "python");
    // 执行函数
    PyObject_CallObject(pFunc, str);    


    /**************************
     * ******class A测试*****
    **************************/
   PyObject* pDict = PyModule_GetDict(pModule);
    // 类
    PyObject* pClassA = PyDict_GetItemString(pDict, "A");
    // 类的构造对象
    PyObject* pConstruct = PyInstanceMethod_New(pClassA);
    // 类的对象
    PyObject * pInsA = PyObject_CallObject(pConstruct, args);
    // 调用类的方法
    PyObject* result = PyObject_CallMethod(pInsA, "add", nullptr);
    // 对结果进行解读
    if(result != nullptr){
        char * str_result;
        PyArg_Parse(result, "s", &str_result);
        printf("Result: %s\n", str_result);  
        Py_DECREF(result);
    }

    // 终止Python解释器
    Py_Finalize();  

}

结果如下所示:

11
result:11
hello python
11
Result: hello world

Python的C API有很多,这里我们只是用了几个,关于更多的API,请参考官网

参考链接

  1. https://www.52txr.cn/2023/CPytonCython.html
  2. https://www.cnblogs.com/traditional/p/13196509.html
  3. https://chend0316.github.io/backend/cython/#%E7%AC%AC1%E7%AB%A0-cython%E7%9A%84%E5%AE%89%E8%A3%85%E5%92%8C%E4%BD%BF%E7%94%A8
  4. https://blog.csdn.net/u011722929/article/details/114871365
  5. https://www.hbblog.cn/python%26C%2B%2B/python%E5%92%8CC%E7%9A%84%E4%BA%A4%E4%BA%92/#31-pythonapi
  6. https://zhuanlan.zhihu.com/p/79896193
  7. https://blog.csdn.net/qq_42688495/article/details/120563844
  • 26
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值