我能够从C库成功调用函数。 C代码如下所示:
{
void return128bit(*data);
}
我需要传递一个指向128位整数的指针,但是我不确定如何执行此操作。我看到的其他答案都来自Python2,要么不起作用,要么不完全符合我的需求。
[我曾尝试在Python中制作一个128位的结构,像这样对2个条目的64位数组使用c-types,然后我将指针移出:
class c_uint128(Structure):
_fields = [
('value', c_uint64 * 2)
]
def __init__(self, number = 0):
super(c_uint128, self).__init__(number)
我没有尝试将其传递给我,因为我什至无法做一些基本的事情,例如在python中初始化128位结构。我从另一个(已有6年以上历史的答案)中找到的此[[init函数不再起作用,并且出现错误TypeError: too many initializers.
编辑:我也无法通过执行将c_uint128类型转换为指针
data = c_uint128()
datap = c_void_p(data)
TypeError: cannot be converted to pointer
class c_uint128(Structure):
_fields = [
('value', c_uint64 * 2)
]
def __init__(self, number = 0):
super(c_uint128, self).__init__(number)
我意识到_fields
应该是_fields_
,这本身就引起了很多问题。这样,我可以通过添加一些方法来弄清楚如何将其用作128位:
class c_uint128(Structure): _fields_ = [ ('int128', c_uint64 * 2) ] def __init__(self, number = 0): self.int128[0] = number & 0xffffffffffffffff #lower 64 bits self.int128[1] = (number >> 64) & 0xffffffffffffffff #upper 64 bits def __str__(self): return str((self.int128[1] << 64) | self.int128[0]) def value(self): return (self.int128[1] << 64) | self.int128[0]
使用self.value()覆盖算术运算符以将其转换为常规python int使其更容易使用。[将其传递给c函数,我必须使用byref():
def return128bit(data): lib.return128bit(byref(data) data = c_uint128(41243) return128bit(data)