在Python中,如何访问由SWIG包装的uint16[3]数组(即解开PySwigObject)?
这是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中包装的指针所指向的同一内存?
我认为问题有两部分:
- 如何从 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>
然后尝试使用“0x8902f00”和“uint16”构建B(任何向量类型)并测试更改B[2]是否会导致C[2]发生变化。
非常感谢您的建议或明确的例子。
问候,
欧文
This is Python question. I have a variable A
>>> A
<Swig Object of type 'uint16_t *' at 0x8c66fa0>
>>> help(A)
class PySwigObject(object)
Swig object carries a C/C++ instance pointer
The instance referred by A is a contiguous array uint16[3] and the problem is to gain access to that array from Python.
In Python, how can I create a variable B of length 3, that gives me read/write access to the same memory pointed by the pointer wrapped in A?
I think the problem has two parts:
- How to get the pointer out of A. (I think 0x8c66fa0 points to a Swig object, not the wrapped object).
- 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.
This should be easy I think, but I've been reading and hacking for more than a day!
To solve the second part, I think an example could begin this way:
>>> 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>
Then try to build B (of whatever vector type) using "0x8902f00" and "uint16" and test if changing B[2] causes changes in C[2].
Many thanks for your suggestions or a clear example.
Regards,
Owen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过更多的阅读和尝试,答案如下:
那么元素可以被寻址为 pA[0], pA[1] 等
pA 指向与原始对象相同的内存,因此注意不要在之后使用 pA原始对象被删除。
这是问题第二部分的示例(在 Python 中使用已知类型的原始指针),
在 Python 中运行该示例将显示 C[1] 和 pC[1] 都已更改为 100
。 。 :)
After more reading and trying stuff out, the answers are as follows:
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),
Running the example in Python will show that both C[1] and pC[1] have been changed to 100.
Solved. :)