简体   繁体   English

使用ctypes突变整数数组

[英]Mutate an integer array using ctypes

Currently I'm in the process of moving a performance bottleneck in my python code to c, to investigate peformance effects. 目前我正在将我的python代码中的性能瓶颈转移到c,以研究性能影响。 This code will run a simulation, and report back the results to python via ctypes. 此代码将运行模拟,并通过ctypes将结果报告给python。 However, I'm having problems getting my types to match up correctly. 但是,我在让我的类型正确匹配时遇到问题。

Although I'm looking to solve this particular problem, I'm also on the lookout for more general advice on working with ctypes, as the documentation and procedure seems a bit thin. 虽然我正在寻求解决这个特殊问题,但我也在寻找有关使用ctypes的更一般的建议,因为文档和程序看起来有点薄。

I have the following c function: 我有以下c函数:

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

And the following code in python: 以下是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 )

However, this snippet dies with the following traceback: 但是,此代码段会因以下回溯而死亡:

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

Looks like you want the cast function : 看起来你想要演员功能

The cast function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast函数可用于将ctypes实例强制转换为指向不同ctypes数据类型的指针。 cast takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. cast接受两个参数,一个是或者可以转换为某种指针的ctypes对象,以及一个ctypes指针类型。 It returns an instance of the second argument, which references the same memory block as the first argument: 它返回第二个参数的实例,它引用与第一个参数相同的内存块:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM