values = ffi.new( "int[]", 10 )
pValue = ffi.addressof( pInt, 0 )
使用 Python CFFI,上面的代码创建了一个指向 values
的第一个元素的指针作为 pValue
。
然后您可以使用 values[0]
访问它的内容,但这并不是真正透明的,有时不方便跟踪什么索引是什么值。
是否有诸如 C *-operator
之类的函数或其他东西来取消引用 pValue
并直接访问其内容?
在其他语言中...:
// In C:
// =====
int values[ 10 ] = {0};
int* pValue = &( values[ 0 ] );
func_with_pointer_to_int_as_param( pValue );
printf( "%d\n", *pValue );
-------------------------------------------------------------
# In Python with CFFI:
# ====================
values = ffi.new( "int[]", 10 )
pValue = ffi.addressof( values, 0 )
lib.func_with_pointer_to_int_as_param( pValue ) #lib is where the C functions are
print values[ 0 ] #Something else than that? Sort of "ffi.contentof( pValue )"?
编辑:
这是一个有用的用例:
我发现这样做更具可读性:
pC_int = ffi.new( "int[]", 2 )
pType = ffi.addressof( pC_int, 0 )
pValue = ffi.addressof( pC_int, 1 )
...
# That you access with:
print "Type: {0}, value: {1}".format( pC_int[ 0 ], pC_int[ 1 ] )
而不是:
pInt_type = ffi.new( "int[]", 1 )
pType = ffi.addressof( pInt_type, 0 )
pInt_value = ffi.new( "int[]", 1 )
pValue = ffi.addressof( pInt_value, 0 )
...
# That you access with:
print "Type: {0}, value: {1}".format( pInt_type[ 0 ], pInt_value[ 0 ] )
而且我猜前者更快。但是,当你想访问这些值时,它会让人不方便记住,比如“ok type is number 0”等等......
最佳答案
在 C 中,语法 *pType
始终等同于 pType[0]
。所以说你想做这样的事情:
print "Type: {0}, value: {1}".format( *pType, *pValue )
但这当然不是有效的 Python 语法。解决方案是您始终可以像这样重写它,这将成为有效的 Python 语法:
print "Type: {0}, value: {1}".format( pType[0], pValue[0] )
关于python - 在 Python CFFI 中取消引用使用 ffi.addressof 创建的指针(C * - 等效运算符?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38464789/