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

标签 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 引用的实例是一个连续数组 uint16[3],问题是如何从 Python 访问该数组。

在 Python 中,我如何创建一个长度为 3 的变量 B,它使我能够读/写访问 A 中包含的指针指向的同一内存?

我认为这个问题有两个部分:

  1. How to get the pointer out of A. (I think 0x8c66fa0 points to a Swig object, not the wrapped object).
  2. How to initialise some kind of Python array using a memory pointer and a known data type. (Numpy has a frombuffer method, but what seems to be needed is a frommemory method.) Perhaps some casting will be needed.

我认为这应该很容易,但我已经阅读和破解了一天多!

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

>>> 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>

然后尝试使用“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 ) )

Then the elements can be addressed as pA[0], pA[1] etc

pA points to the same memory as the original object, therefore be careful not to use pA after the original object is deleted.

Here is an example for just the second part of the problem (on using a raw pointer of known type in Python),

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

在 Python 中运行示例将显示 C[1] 和 pC[1] 都已更改为 100。

已解决。 :)

关于python - 在 Python 中,如何访问由 SWIG 包装的 uint16[3] 数组(即打开 PySwigObject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2209395/

相关文章:

python - 构建期间在 Dockerfile 中激活和切换 Anaconda 环境

python - Numpy 中数据的功率谱和自相关

python - 如何使用 matplotlib 在线图上叠加散点图?

python - 如何在点击 QTreeWidget 的空白区域时执行函数

c# - CMake、SWIG 和共享库

c++ - Swig、Python、C++ : TypeError: in method 'Geodatabase_Open' , 类型 'std::string' 的参数 2

c++ - SWIG 和 C++ 共享库

Python ctypes 和函数调用

python - 公开 EVP_MD_CTX 的 _hashlib.pyd 内部结构吗?

python - 使用ctypes从python中的C访问结构中的二维数组