【问题标题】:Converting C pointer to Python numpy array将 C 指针转换为 Python numpy 数组
【发布时间】:2022-01-03 16:25:27
【问题描述】:

我是 C 和 Python 中的 ctypes 的新手。

我需要将指向双精度数组的 C 指针转换为 Python numpy 数组。

我的出发点如下:

import ctypes
import numpy as np
arrayPy = np.array([[0, 1, 2], [3, 4, 5]])
out_c = arrayPy.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

请问如何有效地将“out_c”对象转换为 Python numpy 数组?

【问题讨论】:

    标签: python arrays c numpy ctypes


    【解决方案1】:

    起点不正确,因为arrayPy 是一个整数数组。设置dtype 以创建一个双精度数组:

    import ctypes
    import numpy as np
    
    arrayPy = np.array([[0, 1, 2], [3, 4, 5]], dtype=ctypes.c_double)
    out_c = arrayPy.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
    print(out_c, out_c[:arrayPy.size])
    

    输出是一个指向双精度的 C 指针。切片指针将显示数据,但您需要知道大小以不遍历数据的末尾:

    <__main__.LP_c_double object at 0x000001A2B758E3C0> [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
    

    我需要将指向双精度数组的 C 指针转换为 Python numpy 数组。

    要将指针转换回 numpy 数组,如果您知道它的形状,可以使用以下方法:

    a = np.ctypeslib.as_array(out_c, shape=arrayPy.shape)
    print(a)
    

    输出:

    [[0. 1. 2.]
     [3. 4. 5.]]
    

    【讨论】:

    • 谢谢。这种方法解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    相关资源
    最近更新 更多