gpt4 book ai didi

cython - 我怎样才能得到自己的地址?

转载 作者:行者123 更新时间:2023-12-01 05:05:55 25 4
gpt4 key购买 nike

我怎样才能做到这一点:

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失败 Cannot take address of Python variable .
  • &(<PyObject*>self)失败 Taking address of non-lvalue ,我不确定 self实际上是 PyObject* .
  • 最佳答案

    <void*>self<PyObject*>self可以很好地获取指向 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)))

    运行此代码将导致如下结果:

    a=140516369271496
    a=140516369271496
    a=140516369271496
    a=140516369271496
    a.c=140516369271528
    a.py=140516452410632
    cint=140516465032184
    cint=140516465032184
    cint=140516465032264

    关于cython - 我怎样才能得到自己的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28797442/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com