DRz
DRz

Reputation: 1156

Dereferencing a pointer created with ffi.addressof in Python CFFI (C *-operator equivalent?)

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...

Upvotes: 2

Views: 1913

Answers (1)

Armin Rigo
Armin Rigo

Reputation: 12900

In C, the syntax *pType is always equivalent to pType[0]. So say you would like to do something like:

print "Type: {0}, value: {1}".format( *pType, *pValue )

but of course this is not valid Python syntax. The solution is that you can always rewrite it like this, which becomes valid Python syntax:

print "Type: {0}, value: {1}".format( pType[0], pValue[0] )

Upvotes: 1

Related Questions