Python 方法调用 C++ 库中的方法

本文讲述了在将C++库打包为Python共享库时,如何通过修正Python方法调用参数类型、确保参数匹配以及设置PYTHONPATH来解决段错误问题。提供了解决方案和示例代码,包括导入Python模块、创建实例并正确调用方法。
摘要由CSDN通过智能技术生成

当使用 c_types 将 C++ 库打包成共享库 (libSome.so) 以便在 Python 中使用时,调用库中 Python 类的某个方法会产生段错误。问题出现在 Python 的方法调用机制上。
在这里插入图片描述

2. 解决方案

(1) 问题在于尝试使用 PyObject_CallMethod() 调用 Python 方法时,没有传递正确的参数类型。

(2) 正确的调用应该使用 PyObject_CallObject(),它允许传递任意类型和数量的参数。

(3) 此外,需要确保 C++ 代码中传递给 Python 方法的参数与 Python 方法定义中的参数类型相匹配,即 long long -> long,long -> int,double -> float。

(4) 还需要确保 Python 方法的名称与 C++ 代码中尝试调用的名称完全一致,并在 C++ 代码中正确设置环境变量 PYTHONPATH,指向包含 Python 脚本的目录。

以下是修改后的 C++ 代码:

    ...
    /* Funcion de python */
        setenv("PYTHONPATH", ".", 1);

        Py_Initialize();

        PyObject* module = PyImport_ImportModule("filehandler");
        assert(module != NULL);

        PyObject* class = PyObject_GetAttrString(module, "FileHandler");
        assert(class != NULL);

        PyObject* inst = PyInstance_New(class, NULL, NULL);
        assert(inst != NULL);

        PyObject* result = PyObject_CallObject(inst, PyTuple_Pack(4, PyInt_FromLong(ori), PyInt_FromLong(serv), PyInt_FromLong(id), PyFloat_FromDouble(timeStamp)));
        assert(result != NULL);

        Py_Finalize();

代码例子

Python 代码:

class FileHandler:
    def __init__(self):
        self.workingDirectory = os.getcwd()

    def write(self, NodoOrigen, Servicio, Id, payload):
        try:
            os.mkdir(str(NodoOrigen))
        except:
            pass

        os.chdir(str(NodoOrigen) + "/")
        try:
            os.mkdir(str(Servicio))
        except:
            pass

        os.chdir(self.workingDirectory)
        os.chdir(str(NodoOrigen) + "/" + str(Servicio) + "/")
        try:
            f = open(str(Id), "a")
        except:
            print("No se puede abrir el archivo")
        f.write(str(payload))
        f.close()
        os.chdir(self.workingDirectory)

C++ 代码:

#include <Python.h>

...

int main() {
    ...
    // Initialize Python
    Py_Initialize();

    // Import the Python module
    PyObject* module = PyImport_ImportModule("filehandler");
    if (module == NULL) {
        PyErr_Print();
        return 1;
    }

    // Get the Python class
    PyObject* class = PyObject_GetAttrString(module, "FileHandler");
    if (class == NULL) {
        PyErr_Print();
        return 1;
    }

    // Create an instance of the Python class
    PyObject* instance = PyInstance_New(class, NULL, NULL);
    if (instance == NULL) {
        PyErr_Print();
        return 1;
    }

    // Call the Python method
    PyObject* args = PyTuple_Pack(4, PyLong_FromLong(1), PyLong_FromLong(2), PyLong_FromLong(3), PyFloat_FromDouble(4.5));
    if (args == NULL) {
        PyErr_Print();
        return 1;
    }
    PyObject* result = PyObject_CallObject(instance, args);
    if (result == NULL) {
        PyErr_Print();
        return 1;
    }

    // Clean up
    Py_DECREF(result);
    Py_DECREF(args);
    Py_DECREF(instance);
    Py_DECREF(class);
    Py_DECREF(module);
    Py_Finalize();

    return 0;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以通过多种方式调用C++,下面介绍两种常用的方法: 1. ctypes: - ctypes是Python的标准,用于调用动态链接(.dll或.so)中的C函数。 - 首先,将C++代码编译为动态链接。 - 在Python中,使用ctypes模块加载动态链接,并定义函数的原型和参数类型。 - 最后,通过调用加载的函数来使用C++。 - 以下是一个示例代码: ```python import ctypes # 加载动态链接 my_lib = ctypes.CDLL("my_lib.dll") # Windows系统下的示例 # 定义函数原型和参数类型 my_func = my_lib.my_function my_func.argtypes = [ctypes.c_int, ctypes.c_int] my_func.restype = ctypes.c_int # 调用C++函数 result = my_func(3, 5) print(result) ``` 2. Cython: - Cython是一个将Python代码转换为C/C++代码的工具,可以用于编写Python扩展模块。 - 首先,将C++代码编写为Cython模块(.pyx文件)。 - 然后,通过使用Cython编译器将Cython模块编译为C/C++代码。 - 最后,将生成的Python扩展模块导入到Python中使用。 - 以下是一个示例代码: ```python # my_module.pyx cdef extern from "my_lib.h": int my_function(int a, int b) def my_function_wrapper(int a, int b): return my_function(a, b) ``` ```python # setup.py from distutils.core import setup from Cython.Build import cythonize setup( ext_modules=cythonize("my_module.pyx") ) ``` ```bash $ python setup.py build_ext --inplace ``` ```python import my_module result = my_module.my_function_wrapper(3, 5) print(result) ``` 这些方法都有其优缺点,具体取决于你的需求和技术偏好。选择适合你项目的方法后,你就可以在Python调用C++了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值