小工具知识网

当前位置: 首页 > 行业知识 > c++和python的互相调用

行业知识

c++和python的互相调用

2026-10-29 21:44:00 来源:互联网转载

文章目录

  • 前提
  • ctypes
  • pybind11
    • 在python中调用C++
    • 在C++中调用python
    • Cython
      • 加快python速度
      • 在C中调用python代码
      • 调用Python的原生C API
      • 参考��接

        前提

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

        ()

        ctypes

        ctypes 是 Python 的外部函数库。它提供了与 C 兼容的数据类型,并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进行封装。

        上面是ctypes官方文档给出的介绍,通俗理解来说:ctypes可以加载动态链接库,然后以此调用动态链接库中的函数。也就是说,如果我们有一个.c文件,我们可以将它编译成库,然后在python代码里面使用ctypes加载调用它。

        ()

        相关代码如下:

        1. 创建一个main.c文件,包括三个函数,等会我们要通过调用动态链接库的方式在python中调用这三个函数。
        // main.c#include #include int add(int a, int b) {    return a + b;}int sum(int *a, int num){    int sum = 0;    for(int i=0; i        sum += a[i];    }    return sum;}    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");}    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    // 运行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         char * str_result;        PyArg_Parse(result, "s", &str_result);        printf("Result: %s\n", str_result);          Py_DECREF(result);    }    // 终止Python解释器    Py_Finalize();  }

上一篇:网贷备案怎么避免

下一篇:详解,如何清除本地织梦变量?步骤与技巧全解析