繁体   English   中英

将 ctypes.POINTER(ctypes.c_float) 的部分元素转换为 numpy.array

[英]Convert part element of ctypes.POINTER(ctypes.c_float) to numpy.array

我对将 ctypes.POINTER(ctypes.c_float) 转换为 numpy.array 有疑问

float_pointer= ctypes.POINTER(ctypes.c_float)() #100 float data
float_array = numpy.ctypeslib.as_array(float_pointer,shape=(100,)).copy()

上面的代码可以将整个100个float数据转换成一个numpy.array float_array。 是否可以将float_pointer的第10到20个数据转换成一个新的numpy.array? 喜欢

float_array = numpy.ctypeslib.as_array(start address of 10th element,shape=(10,)).copy()

清单:

您可以使用切片( [Python.Docs]:内置类型 - 常见序列操作)。

代码00.py

#!/usr/bin/env python

import ctypes as cts
import sys

import numpy as np


def gen_ctype_ptr(ctype, dim):
    arr = (ctype * dim)(*(ctype(e) for e in range(dim)))
    return cts.cast(arr, cts.POINTER(ctype))


def main(*argv):
    ctype = cts.c_float
    dim = 100
    fp = gen_ctype_ptr(ctype, dim)
    print(fp)
    print(fp[2], fp[dim - 1])
    print(fp[dim])  # !!! Undefined Behavior !!!
    start = 10
    end = 20

    # Method 1:
    arr0 = np.ctypeslib.as_array(fp, shape=(dim,))[start:end].copy()  # Comment .copy() to see a difference
    print("Array 0:", arr0, arr0.dtype, arr0.shape)

    # Method 2:
    arr1 = np.array(fp[start:end], dtype=ctype)
    print("Array 1:", arr1, arr1.dtype, arr1.shape)

    fp[(start + end) // 2] = 99

    print(arr0)
    print(arr1)


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

注意事项

  • 列出了 2 种方法(均使用切片):

    1. 将整个指针数据转换为数组并对其进行切片

    2. 通过切片指针数据创建数组(通过Python列表

我个人更喜欢前一个变体,因为它只复制所需数量的 memory,并且不涉及处理(临时) Python对象(这是昂贵的)。

Output :

 [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q075220805]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe"./code00.py Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec 6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32 <__main__.LP_c_float object at 0x0000018D56ED4BC0> 2.0 99.0 217811481788416.0 Array 0: [10. 11. 12. 13. 14. 15. 16. 17. 18. 19.] float32 (10,) Array 1: [10. 11. 12. 13. 14. 15. 16. 17. 18. 19.] float32 (10,) [10. 11. 12. 13. 14. 15. 16. 17. 18. 19.] [10. 11. 12. 13. 14. 15. 16. 17. 18. 19.] Done.

暂无
暂无

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

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