values = ffi.new( "int[]", 10 )
pValue = ffi.addressof( pInt, 0 )
With Python CFFI, the code above creates a pointer to the first element of values
as pValue
.
You can then access its content with values[ 0 ]
, but this is not really transparent and it is sometimes inconvenient to keep track of what indice is what value.
Is there anything such as the C *-operator
, a function or something else, to dereference pValue
and access its content directly?
In other languages... :
// 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 )"?
EDIT :
Here is a use case where it is useful:
I find it more readable to do:
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 ] )
Rather than:
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 ] )
And I guess the former is faster. But, when you want to access the values it makes it inconvenient to remember like "ok type is number 0" etc...
Copyright Notice:Content Author:「DRz」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/38464789/dereferencing-a-pointer-created-with-ffi-addressof-in-python-cffi-c-operator