Python calls C++ functions and dll methods, which require the use of array pointers and structure pointers.

It turns out that I wrote an algorithm function in C++, and now I want to use Python to test it. I need to use an array pointer to transfer data and a structure pointer to return the result.

cpp code:

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 code

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]

Guess you like

Origin blog.csdn.net/lianbus/article/details/132687429