rust - 类型OnProduce = extern “C” fn不安全

标签 rust

pub type OnProduce = extern "C" fn(*mut ZLMedia, *const u8, size_t);
extern "C" {
    pub fn zlmedia_set_on_produce(zl_media: *mut ZLInstance, on_produce: OnProduce);
}
我得到:
   |
23 |     pub fn zlmedia_set_on_produce(zl_media: *mut ZLInstance, on_produce: OnProduce);
   |                                                                          ^^^^^^^^^ not FFI-safe
   |
   = help: consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct
   = note: this struct has unspecified layout
但无法为类型(仅结构)添加#[repr(C)]。如您所见,OnProduceextern "C"函数。我以为已经是FFI安全的了

最佳答案

正如@Frxstream指出的,这可能是因为ZLMedia不是FFI安全的。
Quote:

The trouble is that in Rust when a struct is repr(Rust) (the default) it is then free to use whatever layout it thinks is most efficient for your program. So this could (hypothetically) be different between two Rust programs and is even more likely to be different if the two programs are compiled with different versions of the Rust compiler.

So for FFI you need an explicitly specified layout. Currently C and transparent are the only stable layouts for structs. There may be more more in the future but that's currently a ways off.


我最近在论坛上对此进行了讨论,您可能有兴趣阅读(报价来源):[link]

关于rust - 类型OnProduce = extern “C” fn不安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64743518/

相关文章:

rust - 减少深度嵌套属性的匹配缩进

rust - 是否可以在不使用匹配的情况下将 Option<Result<T, E>> 转换为 Result<Option<T>, E>?

rust - 如何在成员方法闭包中使用struct self

rust - 如何指定 AsRef 的生命周期?

rust - 赋予调用者对彼此依赖的局部变量的所有权

rust - 如何在 Rust 中释放通过 FFI 分配的 *char?

string - 为什么从标准输入读取用户输入时我的字符串不匹配?

rust - 匹配浮点范围的替代方法

rust - 为什么移动闭包不拥有变量的所有权?

rust - 我如何在 nixpkgs 派生中使用特定的 Rust 构建?