4

我有一个用 C 编写的应用程序。我想在这个应用程序中执行用 JavaScript 编写的用户定义脚本,并允许这些脚本与映射到 JavaScript 命名空间的我的内部 C 变量一起工作。

是否可以使用 NodeJS 将其编译为脚本引擎?

我知道我可以反之亦然:运行 NodeJS 并将我的 C 代码用作 NodeJS 的库,并将 C 变量正确绑定到 JS。但这是不可接受的,因为我的应用程序有一个 GUI 和许多其他模块作为库包含在内,并且很难重写代码以作为 NodeJS 库运行。

由于性能原因,每次我需要运行脚本时,我也不想将 NodeJS 作为外部可执行文件运行。我需要将 NodeJS 保存在内存中,并在整个进程周期中在同一个命名空间中运行脚本。

也许有一些专门用于此目的的 NodeJS 特殊版本?或者我可以这样编译它?

4

3 回答 3

4

这是一个使用 v8 执行一些 javascript 的示例:

int main(int argc, char* argv[]) {

  // Create a string containing the JavaScript source code.
  String source = String::New("'Hello' + ', World'");

  // Compile the source code.
  Script script = Script::Compile(source);

  // Run the script to get the result.
  Value result = script->Run();

  // Convert the result to an ASCII string and print it.
  String::AsciiValue ascii(result);
  printf("%s\n", *ascii);
  return 0;
}

来自:https ://developers.google.com/v8/get_started

于 2012-04-04T00:42:50.167 回答
1

您需要的是 V8 javascript 引擎。在这里查看更多详细信息...

This document discusses these concepts further and introduces others that are key to embedding V8 within your own C++ application.

您可以使用 nodejs 的目的可能是查看它的源代码,了解如何在 V8 引擎之上构建。

这是一个简单例子。

于 2012-04-04T00:34:08.850 回答
0

为什么不探索 Node 的内部结构并“复制”它正在做的事情。然后您可以在 V8 之上构建您的应用程序。毕竟,Node.JS 只是 V8 和几个库 (I/O) 之上的一层,以提供额外的功能。

于 2012-04-04T00:37:22.563 回答