如何在Rust声明式宏中为fn类型添加unsafe extern "C"修饰
用macro_rules生成unsafe extern "C"函数类型定义
完全可以用macro_rules实现这个需求,不需要依赖过程宏。核心是要精准匹配Rust中fn类型的语法结构,以下是具体实现:
宏定义
macro_rules! define_ext_fn_type { // 匹配无返回值的fn类型(默认返回()) (fn($($arg_ty:ty),*), $ident:ident) => { type $ident = unsafe extern "C" fn($($arg_ty),*); }; // 匹配带返回值的fn类型 (fn($($arg_ty:ty),*) -> $ret_ty:ty, $ident:ident) => { type $ident = unsafe extern "C" fn($($arg_ty),*) -> $ret_ty; }; }
使用示例
// 生成无返回值的C函数类型 define_ext_fn_type!(fn(i32), my_function_type); // 生成带返回值的C函数类型 define_ext_fn_type!(fn(i32, f64) -> bool, my_returning_function_type); fn main() { // 验证类型合法性(仅作示例,实际使用需绑定有效函数指针) let _: my_function_type = unsafe { std::mem::zeroed() }; let _: my_returning_function_type = unsafe { std::mem::zeroed() }; }
常见报错原因
之前的报错大概率是因为宏的匹配模式未正确捕获fn类型的参数列表或返回值部分。macro_rules基于token树匹配语法结构,只要严格对应fn(...)和fn(...) -> ...的格式,就能正确生成目标代码。
内容的提问来源于stack exchange,提问作者Finomnis
相关产品推荐
相关产品推荐

