Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何访问SWIG包装的uint16[3]数组(即展开PySwigObject)?_Python_Swig_Ctypes - Fatal编程技术网

在Python中,如何访问SWIG包装的uint16[3]数组(即展开PySwigObject)?

在Python中,如何访问SWIG包装的uint16[3]数组(即展开PySwigObject)?,python,swig,ctypes,Python,Swig,Ctypes,这是Python的问题。我有一个变量a >>> A <Swig Object of type 'uint16_t *' at 0x8c66fa0> >>> help(A) class PySwigObject(object) Swig object carries a C/C++ instance pointer >>A >>>帮助(A) 类PySwigObject(对象) Swig对象携带一个C/C++实例指针 A引用的实例是一个连续数

这是Python的问题。我有一个变量a

>>> A
<Swig Object of type 'uint16_t *' at 0x8c66fa0>

>>> help(A)
class PySwigObject(object)
  Swig object carries a C/C++ instance pointer
>>A
>>>帮助(A)
类PySwigObject(对象)
Swig对象携带一个C/C++实例指针
A引用的实例是一个连续数组uint16[3],问题是如何从Python访问该数组

在Python中,如何创建一个长度为3的变量B,使我能够读/写由封装在a中的指针指向的相同内存

我认为问题有两个方面:

  • 如何将指针从中取出(我认为0x8c66fa0指向Swig对象,而不是包装对象)
  • 如何使用内存指针和已知数据类型初始化某种Python数组。(Numpy有一个frombuffer方法,但似乎需要的是frommemory方法。)也许需要一些强制转换
  • 这应该很容易,我想,但我已经阅读和黑客超过一天

    为了解决第二部分的问题,我认为可以这样开始一个例子:

    >>> import numpy
    >>> C = numpy.ascontiguousarray([5,6,7],"uint16")
    >>> C
    array([5, 6, 7], dtype=uint16)
    >>> C.data
    <read-write buffer for 0x8cd9340, size 6, offset 0 at 0x8902f00>
    
    导入numpy >>>C=numpy.ascontiguousarray([5,6,7],“uint16”) >>>C 数组([5,6,7],dtype=uint16) >>>C.数据 然后尝试使用“0x8902f00”和“uint16”构建B(任何向量类型),并测试更改B[2]是否会导致C[2]中的更改

    非常感谢您的建议或一个明确的例子

    问候,


    欧文

    经过更多的阅读和尝试,答案如下:

    1. The wrapped pointer in PySwigObject A is available as A.__long__() . 2. A raw pointer can be cast into an indexable type using ctypes as follows import ctypes pA = ctypes.cast( A.__long__(), ctypes.POINTER( ctypes.c_uint16 ) ) 在Python中运行该示例将显示C[1]和pC[1]都已更改为100

    已解决。:)

    C = numpy.ascontiguousarray([5,6,7],"uint16")  # make an array
    C
    rawPointer = C.ctypes.data
    pC = ctypes.cast( rawPointer, ctypes.POINTER( ctypes.c_uint16 ))
    pC[0:3]
    pC[1]=100
    pC[0:3]
    C