假设我有一个包含常量或静态变量的Rust API,例如i32.我想使用C中的这个Rust API.从C方面来说,我想使用这个常量作为数组大小.我说的没有办法做对吗?重新声明C头文件中的常量的最佳解决方案是什么?这些头文件为Rust API的其余部分提供声明?
Update:
假设我有一个包含常量或静态变量的Rust API,例如i32.我想使用C中的这个Rust API.从C方面来说,我想使用这个常量作为数组大小.我说的没有办法做对吗?重新声明C头文件中的常量的最佳解决方案是什么?这些头文件为Rust API的其余部分提供声明?
Update:
你肯定能做到,至少在函数内部:
cnst.rs
:
#[no_mangle]
pub static X: i32 = 42;
cnstuse.c
:
#include <stdint.h>
#include <stdio.h>
extern const int32_t X;
int main() {
char data[X];
printf("%lu\n", sizeof(data));
return 0;
}
汇编:
% rustc --crate-type=staticlib cnst.rs
note: link against the following native artifacts when linking against this static library
note: the order and any duplication can be significant on some platforms, and so may need to be preserved
note: library: System
note: library: pthread
note: library: c
note: library: m
% gcc -o cnstuse cnstuse.c libcnst.a
% ./cnstuse
42
然而,顶级数组声明不能使用全局变量/常量来表示大小,因此这只能在函数内部工作.