代码之家  ›  专栏  ›  技术社区  ›  Andrew Walker

使用ctypes更改整数数组

  •  4
  • Andrew Walker  · 技术社区  · 15 年前

    虽然我正在寻找解决这个特殊问题的方法,但我也在寻找关于使用ctypes的更一般的建议,因为文档和过程似乎有点单薄。

    我有以下c函数:

    extern "C" {
        void f( int* array, int arraylen ) {
            for(int i = 0; i < arraylen; i++) {
                array[i] = g() // mutate the value array[i];
            }
        }
    }
    

    以及以下python代码:

    import ctypes
    
    plib   = ctypes.cdll.LoadLibrary('./mylib.so')
    _f = plib.f
    _f.restype  = None
    _f.argtypes = [ ctypes.POINTER(ctypes.c_int), ctypes.c_int ]
    seqlen = 50
    buffer = ctypes.c_int * seqlen
    _f( buffer, seqlen )
    

    但是,此代码段会随着以下回溯而消亡:

    Traceback (most recent call last):
      File "particle.py", line 9, in <module>
        _f( buffer, seqlen )
    ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: expected LP_c_int instance instead of _ctypes.ArrayType
    
    1 回复  |  直到 15 年前
        1
  •  4
  •   Mark Rushakoff    15 年前

    看起来你想要 the cast function :

    cast函数可用于将ctypes实例强制转换为指向不同ctypes数据类型的指针。cast接受两个参数,一个是ctypes对象,它是或可以转换为某种类型的指针,另一个是ctypes指针类型。它返回第二个参数的实例,该实例引用与第一个参数相同的内存块:

    >>> a = (c_byte * 4)()
    >>> a
    <__main__.c_byte_Array_4 object at 0xb7da2df4>
    >>> cast(a, POINTER(c_int))
    <ctypes.LP_c_long object at ...>
    >>>