📤 函数导出
基本函数
rust
use neon::prelude::*;
fn greet(mut cx: FunctionContext) -> JsResult {
Ok(cx.string("Hello!"))
}
#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
cx.export_function("greet", greet)?;
Ok(())
}
使用 #[neon::export] 宏
rust
// 更简洁的方式
#[neon::export]
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[neon::export]
fn greet(name: String) -> String {
format!("Hello, {}!", name)
}
🎯 上下文类型
| 类型 | 用途 |
|---|---|
| FunctionContext | 函数调用上下文 |
| ModuleContext | 模块初始化上下文 |
| CallContext | 通用调用上下文 |
| TaskContext | 异步任务上下文 |
📥 参数获取
rust
fn example(mut cx: FunctionContext) -> JsResult {
// 按索引获取参数
let first: Handle = cx.argument(0)?;
let second: Handle = cx.argument(1)?;
// 获取并转换
let num = cx.argument::(0)?.value(&mut cx);
let text = cx.argument::(1)?.value(&mut cx);
// 可选参数
let optional = cx.argument_opt(2);
if let Some(val) = optional {
let s: Handle = val.downcast_or_throw(&mut cx)?;
}
Ok(cx.undefined())
}
📤 返回值
rust
// 返回字符串
fn get_string(mut cx: FunctionContext) -> JsResult {
Ok(cx.string("Hello"))
}
// 返回数字
fn get_number(mut cx: FunctionContext) -> JsResult {
Ok(cx.number(42.0))
}
// 返回对象
fn get_object(mut cx: FunctionContext) -> JsResult {
let obj = cx.empty_object();
let name = cx.string("Neon");
obj.set(&mut cx, "name", name)?;
Ok(obj)
}
// 返回数组
fn get_array(mut cx: FunctionContext) -> JsResult {
let arr = cx.empty_array();
let val = cx.number(1.0);
arr.set(&mut cx, 0, val)?;
Ok(arr)
}
❌ 错误处理
rust
fn may_fail(mut cx: FunctionContext) -> JsResult {
let input = cx.argument::(0)?.value(&mut cx);
if input.is_empty() {
// 抛出 JavaScript 错误
return cx.throw_error("Input cannot be empty");
}
Ok(cx.string(format!("Got: {}", input)))
}
🔧 常用方法
| 方法 | 说明 |
|---|---|
| cx.string("text") | 创建 JS 字符串 |
| cx.number(42.0) | 创建 JS 数字 |
| cx.boolean(true) | 创建 JS 布尔 |
| cx.empty_object() | 创建空对象 |
| cx.empty_array() | 创建空数组 |
| cx.undefined() | 返回 undefined |
| cx.null() | 返回 null |
| cx.throw_error("msg") | 抛出错误 |