python 调用c++的函数,dll方法,需要用到数组指针与结构体指针

原来c++写了一个算法函数,现在要用Python来测试,需要用到数组指针传递数据,用结构体指针传回结果。

cpp代码:

extern "C" {
    struct Result {
        double value1;
        double value2;
    };

    __declspec(dllexport) void compute_result(Result* result, double* array, int array_size) {
        result->value1 += 1.0;
        result->value2 *= 2.0;
        for (int i = 0; i < array_size; ++i) {
            array[i] += 1.0;
        }
    }
}

Python代码

import ctypes
import numpy as np

# 定义与C++中相同的结构体
class Result(ctypes.Structure):
    _fields_ = [("value1", ctypes.c_double),
                ("value2", ctypes.c_double)]

# 加载DLL
example_dll = ctypes.CDLL('./example.dll')

# 创建一个Result实例
result = Result(1.0, 2.0)

# 创建NumPy数组
arr = np.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float64)
n = arr.shape[0]

# 定义DLL中函数的参数类型和返回类型
example_dll.compute_result.argtypes = [ctypes.POINTER(Result), ctypes.POINTER(ctypes.c_double), ctypes.c_int]
example_dll.compute_result.restype = None

# 调用DLL函数,传入Result实例的指针和NumPy数组的指针
example_dll.compute_result(ctypes.byref(result), arr.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), ctypes.c_int(n))

# 输出修改后的结构体字段和NumPy数组
print("Modified result:")
print("value1:", result.value1)  # 输出应为 2.0
print("value2:", result.value2)  # 输出应为 4.0
print("array:", arr)  # 输出应为 [2.0, 3.0, 4.0, 5.0, 6.0]

猜你喜欢

转载自blog.csdn.net/lianbus/article/details/132687429