#include #include // 示例 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().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().DoubleValue(); double b = info[1].As().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)