- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我已经定义了一个 ctypes
类和一个相关的便利函数,如下所示:
class BNG_FFITuple(Structure):
_fields_ = [("a", c_uint32),
("b", c_uint32)]
class BNG_FFIArray(Structure):
_fields_ = [("data", c_void_p),
("len", c_size_t)]
# Allow implicit conversions from a sequence of 32-bit unsigned ints
@classmethod
def from_param(cls, seq):
return seq if isinstance(seq, cls) else cls(seq)
def __init__(self, seq, data_type = c_float):
array_type = data_type * len(seq)
raw_seq = array_type(*seq)
self.data = cast(raw_seq, c_void_p)
self.len = len(seq)
def bng_void_array_to_tuple_list(array, _func, _args):
res = cast(array.data, POINTER(BNG_FFITuple * array.len))[0]
return res
convert = lib.convert_to_bng
convert.argtypes = (BNG_FFIArray, BNG_FFIArray)
convert.restype = BNG_FFIArray
convert.errcheck = bng_void_array_to_tuple_list
drop_array = lib.drop_array
drop_array.argtypes = (POINTER(BNG_FFIArray),)
然后我定义一个简单的便利函数:
def f(a, b):
return [(i.a, i.b) for i in iter(convert(a, b))]
大部分都可以完美运行,但我有两个问题:
c_float
而不是 c_uint32
实例化 BNG_FFITuple
(所以字段是 c_float
),反之亦然,所以 BNG_FFIArray
data_type
是 c_uint32
。不过,我不清楚如何做到这一点。POINTER(BNG_FFIArray)
发送回我的 dylib(请参阅 drop_array
- 我已经已经在我的 dylib 中定义了一个函数),但我不确定应该在什么时候调用它。有没有办法以一种更整洁、更 Python 的方式封装所有这些,也更安全?我担心如果没有以稳健的方式定义内存清理(在 __exit__
?__del__
?)出现任何问题都会导致内存未释放
最佳答案
由于您对 rust 方面有一定的控制权,因此最简单的做法是在调用之前从 Python 预先分配结果数组,并将所有内容传递到单个结构中。
下面的代码假定了这种修改,但也指定了如果你不能这样做,你将在哪里进行释放。
请注意,如果您进行这种封装,则不需要为库函数指定参数和结果处理等内容,因为您只是从一个地方调用实际函数,并且始终使用完全相同的相同类型的参数。
我不知道 rust(甚至我的 C 有点生锈),但下面的代码假设您重新定义 rust 以匹配类似这样的内容:
typedef struct FFIParams {
int32 source_ints;
int32 len;
void * a;
void * b;
void * result;
} FFIParams;
void convert_to_bng(FFIParams *p) {
}
这里是 Python。最后一点——由于参数结构的重用,这不是线程安全的。如果需要,这很容易解决。
from ctypes import c_uint32, c_float, c_size_t, c_void_p
from ctypes import Structure, POINTER, pointer, cast
from itertools import izip, islice
_test_standalone = __name__ == '__main__'
if _test_standalone:
class lib(object):
@staticmethod
def convert_to_bng(ptr_params):
params = ptr_params.contents
source_ints = params.source_ints
types = c_uint32, c_float
if not source_ints:
types = reversed(types)
length = params.len
src_type, dst_type = types
src_type = POINTER(length * src_type)
dst_type = POINTER(length * 2 * dst_type)
a = cast(params.a, src_type).contents
b = cast(params.b, src_type).contents
result = cast(params.result, dst_type).contents
# Assumes we are converting int to float or back...
func = float if source_ints else int
result[0::2] = map(func, a)
result[1::2] = map(func, b)
class _BNG_FFIParams(Structure):
_fields_ = [("source_ints", c_uint32),
("len", c_size_t),
("a", c_void_p),
("b", c_void_p),
("result", c_void_p)]
class _BNG_FFI(object):
int_type = c_uint32
float_type = c_float
_array_type = type(10 * int_type)
# This assumes we want the result to be opposite type.
# Maybe I misunderstood this -- easily fixable if so.
_result_type = {int_type: float_type, float_type: int_type}
def __init__(self):
my_params = _BNG_FFIParams()
self._params = my_params
self._pointer = POINTER(_BNG_FFIParams)(my_params)
self._converter = lib.convert_to_bng
def _getarray(self, seq, data_type):
# Optimization for pre-allocated correct array type
if type(type(seq)) == self._array_type and seq._type_ is data_type:
print("Optimized!")
return seq
return (data_type * len(seq))(*seq)
def __call__(self, a, b, data_type=float_type):
length = len(a)
if length != len(b):
raise ValueError("Input lengths must be same")
a, b = (self._getarray(x, data_type) for x in (a, b))
# This has the salutary side-effect of insuring we were
# passed a valid type
result = (length * 2 * self._result_type[data_type])()
params = self._params
params.source_ints = data_type is self.int_type
params.len = length
params.a = cast(pointer(a), c_void_p)
params.b = cast(pointer(b), c_void_p)
params.result = cast(pointer(result), c_void_p)
self._converter(self._pointer)
evens = islice(result, 0, None, 2)
odds = islice(result, 1, None, 2)
result = list(izip(evens, odds))
# If you have to have the converter allocate memory,
# deallocate it here...
return result
convert = _BNG_FFI()
if _test_standalone:
print(convert([1.0, 2.0, 3.0], [4.0, 5.0, 6.0], c_float))
print(convert([1, 2, 3], [4, 5, 6], c_uint32))
print(convert([1, 2, 3], (c_uint32 * 3)(4, 5, 6), c_uint32))
关于python - 构建 ctypes 类的简洁方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31316766/
我似乎找不到任何将 ctypes.c_void_p() 转换为字符串或字节数组的简单示例。有没有简单的衬里可以做到这一点? 最佳答案 给你: import ctypes as ct # set up
在ctypes中,pointer和byref有什么区别?它们似乎都是将指针传递给函数的一种方式,例如作为输出参数。 最佳答案 在功能上,它们是等价的。 然而,python docs请指出 pointe
我知道我应该指定 argtypes对于我的 C/C++ 函数,因为我的某些调用会导致堆栈损坏。 myCfunc.argtypes = [ct.c_void_p, ct.POINTER(ct.c
有没有办法获取指向 ctypes 数组中间元素的指针?示例: lib = ctypes.cdll.LoadLibrary('./lib.so') arr = (ctypes.c_int32 * 100
在我自定义的 TYPO3 Extbase 扩展中,我创建了一个后端模块来管理个人记录。现在我需要一个内容元素来在前端显示记录。 我看到了两种实现此目的的方法: 使用 CType“list”和自定义 l
实际上,我正在尝试将 ctypes 数组转换为 python 列表并返回。 如果找到this thread 。但它假设我们在编译时知道类型。 但是是否可以检索元素的 ctypes 类型? 我有一个 p
我正在将 float 列表转换为具有以下字段的 ctypes Structure 类,然后再将它们传递给 FFI 函数: FFIArray(Structure): _fields_ = [("
我需要将异质数据的二维数组从我的 c dll 返回到 python。 为此目的,我从我的 c dll 返回一个元组的元组。它作为 PyObject 返回 * 这个元组的元组需要作为第一行第一列的 tu
这是不一致的: from ctypes import * class S(Structure): _fields_ = [("x", POINTER(c_int)), ("y", c_int)
我真的希望一些 Python/Ctypes/C 专家可以帮助我解决这个问题,这可能是我在使用 Python 与 C 库交互时正确使用 Ctypes 的类型结构方面缺乏知识。 目标:我需要访问几个使用
我正在尝试调试 python 使用 ctypes 调用 C 函数的代码。我感兴趣的 python 代码中的一行看起来像: returnValue = cfunction() 其中 cfunction
我正在开发 DLL/SO 的 Python 包装器。我已经验证了代码可以调用实际的 DLL 和 SO。我想对我的包装器进行单元测试,而不需要安装底层 DLL/SO。我正在考虑使用 mock 。 我遇到
大家。我在使用 ctypes 和 C 代码时遇到内存分配错误。我想知道内存问题是在 C 内部,还是由 ctypes 使用不当引起的。内存错误是 python(79698) malloc: * erro
我想制作一个笑话程序,首先它打开一个消息框,关闭后另一个消息框出现在随机位置。它会一直这样重复,直到有什么东西终止了它的任务。使用 tkinter 消息框,那么这些消息框就无法被 Hook ,我必须制
我对 python 中的变量大小有疑问,我使用 Ctypes 因为我想要一个 1 字节的数字,但是当我试图在 python 中检查它的大小时(通过 sys.getsize ) 它说它是 80 字节但是
我正在尝试在 python lambda 函数中使用 matplotlib 生成图形。我使用库 mathplotlib 导入了一个图层,但它不起作用。 这个想法是生成一个图形,将其保存为临时文件并上传
我正在尝试使用 C 中的 python ctypes 制作简单的库 blake 哈希函数包装器。但只是为了首先测试我的简单 C 辅助函数是否能正常工作,我编写了小的 python 脚本 blake 哈
图书馆代码(简化版): // package1.go package package1 import "C" func Play(s *C.char) { } 客户代码: // main.go pac
到目前为止,我已经得到了一个不适用于 python 的 DLL,并输入 return: I just can't pass it arguments because I doing it wrong
我有一个具有以下签名的 C 函数: void init(int* argc, char** argv[]); 我想使用 Ctypes 从我的 OCaml 代码中调用此函数,但我想不出一个正确的方法来传
我是一名优秀的程序员,十分优秀!