Spaces:
Sleeping
Sleeping
File size: 1,294 Bytes
dc21909 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #include <napi.h>
#include <string>
// 示例 N-API 函数
Napi::String Hello(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
std::string name = "World";
if (info.Length() > 0 && info[0].IsString()) {
name = info[0].As<Napi::String>().Utf8Value();
}
std::string result = "Hello, " + name + " from N-API!";
return Napi::String::New(env, result);
}
// 计算函数示例
Napi::Number Add(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
Napi::TypeError::New(env, "需要两个参数").ThrowAsJavaScriptException();
return Napi::Number::New(env, 0);
}
if (!info[0].IsNumber() || !info[1].IsNumber()) {
Napi::TypeError::New(env, "参数必须是数字").ThrowAsJavaScriptException();
return Napi::Number::New(env, 0);
}
double a = info[0].As<Napi::Number>().DoubleValue();
double b = info[1].As<Napi::Number>().DoubleValue();
return Napi::Number::New(env, a + b);
}
// 初始化函数
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "hello"),
Napi::Function::New(env, Hello));
exports.Set(Napi::String::New(env, "add"),
Napi::Function::New(env, Add));
return exports;
}
NODE_API_MODULE(addon, Init) |