2016-07-19 36 views
1
values = ffi.new("int[]", 10) 
pValue = ffi.addressof(pInt, 0) 

使用Python CFFI使用Python CFFI(C * - 运算符等效?)ffi.addressof创建的指针,上面的代码创建的指针的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类型为数字0”等...

+1

在C中,'* x'是完全等效于'X [0]'。 –

+0

是的。我添加了一个用例,它有一个直接取消引用CData的指针是有用的。 – DRz

+1

对不起,我还是不明白。你想干什么?那是你用C编写的'* pType','* pValue'吗?然后你可以写它'pType [0]','pValue [0]'。当然你也可以定义和使用你自己的函数def contentof(p):return p [0]'。 –

回答

1

在C中,语法*pType总是等于pType[0]。所以说你想做类似的事情:

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

但当然这是无效的Python语法。该解决方案是,可以随时重写它像这样,成为有效的Python语法:

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