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

使用ctypes修改整数数组

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

    我有以下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 回复  |  直到 16 年前
        1
  •  4
  •   Mark Rushakoff    16 年前

    看起来你想要 the cast function :

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

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