我如何获得自己的地址? [英] How can I get the address of self?
本文介绍了我如何获得自己的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么做:
cdef class Tree:
cdef object key
cdef Tree left
cdef Tree right
cdef PyObject** find(self, key):
# get the address of self
# return &self
# return &(<PyObject*>self)
-
& self
失败,并显示无法获取Python变量的地址
。 -
&(< PyObject *> self)
失败,并显示接收非左值的地址
,而且我不确定self
实际是PyObject *
。 &self
fails withCannot take address of Python variable
.&(<PyObject*>self)
fails withTaking address of non-lvalue
, and I'm not sure thatself
is actually aPyObject*
.
推荐答案
< void *>自我
和< PyObject *> self
可以很好地获得指向self的指针。
<void*>self
and <PyObject*>self
works just fine to get a pointer to self.
from ctypes import addressof, c_int
from cpython.ref cimport PyObject
from cython.operator import address
from libc.stdio cimport printf
cdef class A:
cdef object py
cdef int c
def __init__(self, py, c):
self.py = py
self.c = c
cdef void* addrvoid(self):
return <void*>self
cdef PyObject* addr(self):
return <PyObject*>self
cpdef run():
cdef A a
a = A([], 1)
# these are all equivalent
printf('a=%lu\n', <void*>a)
printf('a=%lu\n', <PyObject*>a)
printf('a=%lu\n', a.addrvoid())
printf('a=%lu\n', a.addr())
# type casting doesnt work with the extension's c attributes because it
# will translate to the arrow operator, like: (void *)__pyx_v_a->b)
# printf('%lu\n', <void*>a.c)
# printf('%lu\n', <void*>(a.c))
# printf('%lu\n', <PyObject*>(a.c))
# and address() dont work with python attributes
# printf('a.py=%lu\n', <void*>address(a.py))
# but address works with c attributes
printf('a.c=%lu\n', address(a.c))
# and type casting works with python attributes
printf('a.py=%lu\n', <void*>(a.py))
# it works with ctypes too
i = c_int(1)
print('cint=' + str(id(i)))
printf('cint=%lu\n', <void*>i)
# but it evaluates to the address of the python object
print('cint=' + str(addressof(i)))
运行此代码将得到类似的结果
Running this code will result in something like:
a = 140516369271496
a = 140516369271496
a = 140516369271496
a = 140516369271496
ac = 140516369271528
a.py = 140516452410632
cint = 140516465032184
cint = 140516465032184
cint = 140516465032264
a=140516369271496
a=140516369271496
a=140516369271496
a=140516369271496
a.c=140516369271528
a.py=140516452410632
cint=140516465032184
cint=140516465032184
cint=140516465032264
这篇关于我如何获得自己的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文