在为 ffi 分配内存时,我试图让我的代码更加健壮。
我写了以下函数:
void withMemory<T extends NativeType>(
int size, void Function(Pointer<T> memory) action) {
final memory = calloc<Int8>(size);
try {
action(memory.cast());
} finally {
calloc.free(memory);
}
}
要调用上述函数,我使用:
withMemory<Uint32>(sizeOf<Uint32>(), (phToken) {
// use the memory allocated to phToken
});
这可行,但正如您所见,我需要通过两次 Uint32 以及sizeOf
.
我真正想写的是:
withMemory<Uint32>((phToken) {
// use the memory allocated to phToken
});
问题是您不能将泛型类型传递给错误calloc
或sizeOf
没有错误:
[...] 的类型参数必须是编译时常量,但类型参数不是常量。尝试将类型参数更改为常量类型。
有没有办法解决这个问题?