繁体   English   中英

如何使用 CTypes 通过引用将数组从 python 传递到 C++ function?

[英]How do you pass an array by reference from python to a C++ function using CTypes?

正如标题所说,在过去的 48 小时里,我一直在尝试将向量从 python 项目传递到我编写的一组 C++ 函数。 最终我得出的结论是使用 arrays 可能更容易,而不是基于对这里过去帖子的一些阅读的向量。 这导致我尝试下面的教程,但它最初只是为了举例说明传入 integer 并返回它。 我尝试更改代码,以便它通过引用传递来自 python 的 3 个数字长列表/数组,然后将其中的每个数字加 1。 然而,当我运行它时,我可以看到它正在获取数组没有问题并打印在 c++ function 中修改的值,但它没有修改原始的 python 变量。 事实上,当我尝试打印包装器 function 的 output 时,我得到的是“<class ' main .c_double_Array_3'>”。下面是我到目前为止尝试过的代码(处于当前状态)。 如果有人可以提供有关资源的一些指导,以获得有关如何执行此操作的清晰教程,或者提供一些有关如何操作的帮助,我将不胜感激。

Simple_calculations C++ 文件

extern "C" void our_function(double * numbers) {
    numbers[0] += 1;
    numbers[1] += 1;
    numbers[2] += 1;
    std::cout << numbers[0] << std::endl;
    std::cout << numbers[1] << std::endl;
    std::cout << numbers[2] << std::endl;
}

Python 文件

import os

import ctypes

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    os.system('g++ -dynamiclib -shared -o simple_calculations.dylib simple_calculations.cpp -std=c++17')

    _sum = ctypes.CDLL('simple_calculations.dylib')
    _sum.our_function.argtypes = (ctypes.POINTER(ctypes.c_double),)

    def our_function(numbers):
        array_type = ctypes.c_double * 3
        _sum.our_function(array_type(*numbers))
        return array_type

    z = our_function([0, 1, 2])

    print(z)

Output

1
2
3
<class '__main__.c_double_Array_3'>

您正在返回array_type 那是一个type ,而不是该类型的一个实例。 该实例是您传递给 function 的array_type(*numbers) ,但未保留。 将它分配给一个变量并返回,或者更好地将它转换回 Python 列表,如下所示:

测试.cpp

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

extern "C" API void our_function(double * numbers) {
    numbers[0] += 1;
    numbers[1] += 1;
    numbers[2] += 1;
}

测试.py

import ctypes

_sum = ctypes.CDLL('./test')
_sum.our_function.argtypes = ctypes.POINTER(ctypes.c_double),

def our_function(numbers):
    array_type = ctypes.c_double * 3  # equiv. to C double[3] type
    arr = array_type(*numbers)        # equiv. to double arr[3] = {...} instance
    _sum.our_function(arr)  # pointer to array passed to function and modified
    return list(arr)        # extract Python floats from ctypes-wrapped array

z = our_function([0, 1, 2])
print(z)

Output:

[1.0, 2.0, 3.0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM