values = ffi.new( "int[]", 10 )
pValue = ffi.addressof( pInt, 0 )
使用 Python CFFI,上面的代码创建了一个指向 as 的第一个元素的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”等不方便......