且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用Rust封装现有的C函数或如何从Rust调用C函数?

更新时间:2023-12-02 23:28:04

如果您尝试从Rust调用C代码,则需要创建FFI绑定,就像某些人在评论中提到的那样.

If you're trying to call C code from Rust, you need to create FFI bindings as some people have mentioned in the comments.

但是,通常***通过 rust-bindgen ,它会自动生成绑定并包括测试以确保结果的大小正确,对齐等.创建大小错误的类型非常容易,这在编译时不会给您任何警告,并且可以导致不确定的行为,除非您使用bindgen为它们生成测试.

However, it is usually best to do this via rust-bindgen, which automatically generates the bindings and includes tests to make sure that the results are properly sized, aligned, etc. It is very easy to create a type with an incorrect size, which will give you no warning at compile-time and can cause undefined behavior unless you generate tests for them with bindgen.