Python:ctypes指向局部变量的指针;如何确保他们不被释放?

时间:2011-07-23 13:23:42

标签: python pointers ctypes

我有一些与此类似的代码:

def castArgToCtype(arg, ctyp):
    if issubclass(ctyp, _ctypes._Pointer): return createPtr(arg, ctyp)
    return ctyp(arg)

def createPtr(arg, ctyp):
    assert isinstance(arg, (list,tuple))
    assert issubclass(ctyp, _ctypes._Pointer)
    o = (ctyp._type_ * (len(arg) + 1))()
    for i in xrange(len(arg)):
        o[i] = castArgToCtype(arg[i], ctyp._type_)
    op = ctypes.cast(ctypes.addressof(o), ctyp)
    # TODO: what when 'o' goes out of scope and freed?
    return op

我称之为createPtr((1,2,3), ctypes.POINTER(ctypes.c_int))

如果没有释放o,我怎样才能确保我在那里创建的ctpes数组op没有被释放?

我已经看到属性op._objects,它似乎就是为了这个目的而存在,但它是只读的。

2 个答案:

答案 0 :(得分:1)

这似乎有效:

import ctypes, _ctypes

def castArgToCtype(arg, ctyp):
    if issubclass(ctyp, _ctypes._Pointer): return createPtr(arg, ctyp)
    return ctyp(arg)

def createPtr(arg, ctyp):
    assert isinstance(arg, (list,tuple))
    assert issubclass(ctyp, _ctypes._Pointer)
    o = (ctyp._type_ * (len(arg) + 1))()
    for i in xrange(len(arg)):
        o[i] = castArgToCtype(arg[i], ctyp._type_)
    op = ctypes.pointer(o)
    op = ctypes.cast(op, ctyp)
    return op

a = createPtr((1,2,3), ctypes.POINTER(ctypes.c_int))
print a, a[0], a[1], a[2], a._objects

输出:

<__main__.LP_c_int object at 0x105dc6680> 1 2 3 {'1': <__main__.c_int_Array_4 object at 0x105dc6560>, '0': {}, 4393297392: <__main__.LP_c_int_Array_4 object at 0x105dc65f0>}

答案 1 :(得分:0)

不需要额外的迭代。只需创建数组对象并将其强制转换为所需的指针。

import ctypes,_ctypes
def castArgToCtype(arg, ctyp):
    if issubclass(ctyp, _ctypes._Pointer): return createPtr(arg, ctyp)
    return ctyp(arg)

def createPtr(arg, ctyp):
    assert isinstance(arg, (list,tuple))
    assert issubclass(ctyp, _ctypes._Pointer)
    return ctypes.cast((ctyp._type_ * len(arg))(*arg),ctyp)

a = castArgToCtype((1,2,3),ctypes.POINTER(ctypes.c_int))
print a,a[0],a[1],a[2],a._objects

输出

<x.LP_c_long object at 0x00EB7760> 1 2 3 {15431440: <ctypes._endian.c_long_Array_3 object at 0x00EB7710>}