从 NodeJS 到 C++ 我应该如何传递参数并获得结果

From NodeJS to C++ how shall I pass arguments and get the result

本文关键字:参数 结果 何传递 NodeJS C++ 我应该      更新时间:2023-10-16

我正在尝试将我的旧C++项目与NodeJS集成。我已经看过你好单词插件教程,将简单的文件 c++ 文件构建到 NodeJS 中。我正在寻找一些高级示例,如果有人致力于构建从 NodeJS 到 C++ 的桥梁。我想将数据从我的nodeJS程序(hello.js(传递到C++程序(hello.cc(

感谢您的帮助

您需要安装 node-gyp - 您可能已经安装了 npm install -g node-gyp

有一个非常好的例子,请看一下https://gist.githubusercontent.com/bengfarrell/4440739/raw/56e8291a31eb8f9714f8ca975c1e78a0788ae018/randomcoords.cpp

如果您无法访问,请告诉我我会在这里通过它

运行此示例像往常一样,您需要构建它,然后创建一个 binding.gyp 文件

{
  "targets": [
    {
      "target_name": "randomcoords",
      "sources": [ "randomcoords.cc" ]
    }
  ]
}

现在在这个 c++ 插件中,你可以传递这样的参数

var randCoords = require("./libs/build/Release/randomcoords.node");
var cursor = randCoords.getRandomCoords3D(600, 400, 100); // params are max values for random output
console.log('{ "x":' + cursor.x +  ', "y":' + cursor.y + ', "z":' + cursor.z + '}');

有一篇又好又短的文章http://www.benfarrell.com/2013/01/03/c-and-node-js-an-unholy-combination-but-oh-so-right/

您可以在以下位置找到使用 NAN 创建本机插件的示例:

  • https://github.com/nodejs/node-addon-examples
  • https://github.com/nodejs/nan#example