在 C 中使用 Rust 函数
在 C 中使用 Rust 函数主要通过 Rust 构建动态库,然后 C 使用该动态库来实现。
构建动态库
首先要创建一个动态库项目,使用命令 cargo new hello --lib
。
我们需要指明库类型为动态库,在 Cargo.toml 文件中添加
[lib]
name = "hello"
crate-type = ["cdylib"]
在 lib.rs 中添加一个最简单的函数
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}
上面的代码是 Keyword extern 中提到的将 Rust 函数导出到 C lib 中的标准做法,根据这篇帖子,extern
和 extern "C"
实际上没有区别,因为 Rust 默认使用标准 C ABI 的格式导出。
然后运行 cargo build
命令构建后就可以在 target/debug
下面找到 libadd.so
库文件(Linux 平台,其它系统的后缀不一样)。
构建头文件
在 C 语言中编写库时,通常会在头文件(.h)中包含所有的声明,在 .c 文件中包含所有的实现。在使用时,需要在代码中 include 对应的头文件才能找到对应的声明。但是 Rust 构建出的动态库并没有生成任何头文件。
我们可以直接自己写一个头文件,但是更好的做法是使用 cbindgen 工具。这个工具为你的 Rust 项目中公开的 C API 生成 C/C++11 头文件。
cbindgen 接受一个 .toml 作为配置文件,这里使用的模板为
# This is a template cbindgen.toml file with all of the default values.
# Some values are commented out because their absence is the real default.
#
# See https://github.com/mozilla/cbindgen/blob/master/docs.md#cbindgentoml
# for detailed documentation of every option here.
language = "C"
############## Options for Wrapping the Contents of the Header #################
# header = "/* Text to put at the beginning of the generated file. Probably a license. */"
# trailer = "/* Text to put at the end of the generated file */"
# include_guard = "my_bindings_h"
# pragma_once = true
# autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */"
include_version = false
# namespace = "my_namespace"
namespaces = []
using_namespaces = []
sys_includes = []
includes = []
no_includes = false
# cpp_compat = true
after_includes = ""
############################ Code Style Options ################################
braces = "SameLine"
line_length = 100
tab_width = 4
documentation = true
documentation_style = "auto"
documentation_length = "full"
line_endings = "LF" # also "CR", "CRLF", "Native"
############################# Codegen Options ##################################
style = "both"
sort_by = "Name" # default for `fn.sort_by` and `const.sort_by`
usize_is_size_t = true
[defines]
# "target_os = freebsd" = "DEFINE_FREEBSD"
# "feature = serde" = "DEFINE_SERDE"
[export]
include = []
exclude = []
# prefix = "CAPI_"
item_types = []
renaming_overrides_prefixing = false
[export.rename]
[export.body]
[export.mangle]
[fn]
rename_args = "None"
# must_use = "MUST_USE_FUNC"
# deprecated = "DEPRECATED_FUNC"
# deprecated_with_note = "DEPRECATED_FUNC_WITH_NOTE"
# no_return = "NO_RETURN"
# prefix = "START_FUNC"
# postfix = "END_FUNC"
args = "auto"
sort_by = "Name"
[struct]
rename_fields = "None"
# must_use = "MUST_USE_STRUCT"
# deprecated = "DEPRECATED_STRUCT"
# deprecated_with_note = "DEPRECATED_STRUCT_WITH_NOTE"
derive_constructor = false
derive_eq = false
derive_neq = false
derive_lt = false
derive_lte = false
derive_gt = false
derive_gte = false
[enum]
rename_variants = "None"
# must_use = "MUST_USE_ENUM"
# deprecated = "DEPRECATED_ENUM"
# deprecated_with_note = "DEPRECATED_ENUM_WITH_NOTE"
add_sentinel = false
prefix_with_name = false
derive_helper_methods = false
derive_const_casts = false
derive_mut_casts = false
# cast_assert_name = "ASSERT"
derive_tagged_enum_destructor = false
derive_tagged_enum_copy_constructor = false
enum_class = true
private_default_tagged_enum_constructor = false
[const]
allow_static_const = true
allow_constexpr = false
sort_by = "Name"
[macro_expansion]
bitflags = false
############## Options for How Your Rust library Should Be Parsed ##############
[parse]
parse_deps = false
# include = []
exclude = []
clean = false
extra_bindings = []
[parse.expand]
crates = []
all_features = false
default_features = true
features = []
然后使用命令 cbindgen --config cbindgen.toml --crate cdylib --output add.h
就可以生成一个 add.h 头文件,
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
int32_t add(int32_t a, int32_t b);
就是 Rust add
函数的等效声明。
接下来的过程就和在 C 中使用动态库的步骤一致了。
WELCOME TO THE MACHINE