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”等...
在C中,'* x'是完全等效于'X [0]'。 –
是的。我添加了一个用例,它有一个直接取消引用CData的指针是有用的。 – DRz
对不起,我还是不明白。你想干什么?那是你用C编写的'* pType','* pValue'吗?然后你可以写它'pType [0]','pValue [0]'。当然你也可以定义和使用你自己的函数def contentof(p):return p [0]'。 –