使用node.js从C ++调用JavaScript [英] Calling JavaScript from C++ with node.js
问题描述
是否可以通过node.js从C ++调用JS函数(作为回调或类似方法)?
如果是,如何?
我正在网上搜索它,但没有找到任何有用的资源。
Is there a way to call JS functions from C++ through node.js (as callbacks or something like that)? If yes, how? I'm searching for it on the web, but haven't found any helpful resource.
预先感谢
推荐答案
形成本机插件的一种方法是使用提供的函数作为回调,例如,让我们假设您有一个名为<$ c $的函数。在您的本机环境(本机附加组件)中声明的c> setPrintFunction():
One way to do it form a native addon can be using the provided function as a callback, for example let's gonna assume that you have a function named setPrintFunction()
declared in your native environment (A native addon):
(例如,调用 main .cc
)
#include <node.h>
#include <string>
v8::Persistent<v8::Function> fn;
// Call this at any time, but after the capture!
void printToNode(std::string msg) {
auto isolate = fn->GetIsolate();
// This part is the one that transforms your std::string to a javascript
// string, and passes it as the first argument:
const unsigned argc = 1;
auto argv[argc] = {
v8::String::NewFromUtf8(isolate,
msg.c_str(),
v8::NewStringType::kNormal).ToLocalChecked()
};
cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
}
// This is your native function that captures the reference
void setPrintFunction(const v8::FunctionCallbackInfo<Value>& args) {
auto isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
auto cb = v8::Local<v8::Function>::Cast(args[0]);
fn = v8::Persistent<v8::Function>::New(cb);
}
// This part exports the function
void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
NODE_SET_METHOD(module, "exports", setPrintFunction);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
然后,只需导入您的插件并使用它即可:
Then, just importing your addon and using it like:
(例如,以 index.js
为例)
const { setPrintFunction } = require('<your path to .node file>');
function printNodeMsg(msg) {
console.log('<msg>: ' + msg);
}
setPrintFunction(printNodeMsg);
因此,您基本上要做的是捕获对 v8的引用: :Function
(这是javascript函数,但在本机环境中),然后调用它并传递 Hello World!
作为第一个(和唯一)参数。
So what you're basically doing is capturing the reference to the v8::Function
(Which is the javascript function, but in the native environment) and then invoking it and passing "Hello World!"
as the first (and unique) parameter.
有关此主题的更多信息: https://nodejs.org/api/addons.html
More on the subject: https://nodejs.org/api/addons.html
这篇关于使用node.js从C ++调用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!