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]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值