c++ - 未调用 NodeJS 嵌套函数的 C++ 插件
问题描述
我正在使用实现 minimax tic-tac-toe AI 的 v8 编写一个 c++ NodeJs 本机插件。
我有一个嵌套函数不起作用的问题。
这是我的代码:
namespace Game {
Move bestMove(...) {
// implementation
}
}
namespace addon {
using namespace v8;
using std::vector;
...
// this function returns the best move back to nodejs
void bestMove(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
...
auto returnVal = Game::bestMove(params); // Game::bestMove() returns the best move for the computer
args.GetReturnValue().Set((returnVal.row * 3) + returnVal.col); // returns the move back to nodejs
}
通常,如果游戏板是这样的(电脑是o):
x _ _
_ _ _
_ _ _
该函数不应返回0
,因为它已被x
. 然而它似乎总是返回0
。
在我调查了一下之后,我意识到这个函数Game::bestMove()
永远不会被调用。
添加是的,我知道这是问题所在,因为在我添加std::cout << "Computing";
函数后Move bestMove()
,它从未打印到控制台。
但是,如果我添加std::cout << "Computing";
函数addon::bestMove()
,它就可以工作。
也没有抛出编译时错误。
谢谢你的帮助。
解决方案
仅当您愿意通过 C++ 绑定 node-addon-api(可通过 npm 获得)使用 N-API 时,此答案才有用。您使用的是 C++,因此它可能是使编码更直接且可能工作的最简洁的方法。Net,我无法从发布的内容中告诉您您的代码有什么问题,因此,如果那是阻碍,则无需继续阅读。
使用 node-addon-api 你的插件看起来像:
#include <napi.h>
// your move function
Napi::Value bestMove(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
int move = Game::bestMove(params);
// just return the number and the C++ inline wrappers handle
// the details
return Napi::Number::New(env, move);
}
// the module init function used in the NODE_API_MODULES macro below
Napi::Object Init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
// expose the bestMove function on the exports object.
exports.Set("bestMove", Napi::Function::New(env, bestMove));
return exports;
}
NODE_API_MODULES(my_game, Init)
在 JavaScript 中,您只需要绑定文件,通常在build/Release/my_game.node
(或使用绑定包,因此您可以只需要('my_game'))。所以
const game = require('my_game')
...
move = game.bestMove()
我不知道足够的细节来更好地充实这个例子。
我在 node-addon-api 包之前与 Nan 一起工作,发现它令人沮丧。我没有尝试直接使用 V8,因为它将我的应用程序绑定到特定版本的节点。
如果您对更多详细信息感兴趣,请查看https://github.com/nodejs/node-addon-api。它真的做得很好。
如果上述任何代码有错误,我们深表歉意;我只是边走边编的。
推荐阅读
- html - 如何使用css调整图像大小以填充行?
- c - 从文件 c 中读取
- graphql - Graphql 查询节点执行顺序
- angular - 如果在离子中,用 ng 承诺
- amazon-web-services - AWS SQS 队列 url 的格式
- android - react-native npm 模块中的第 3 方 maven 依赖项
- python - Python - 从 csv 读取数据,然后使用循环中的数据和文件号写入新的 csv
- node.js - 在网站中引入翻译后的 React 组件的最佳实践?
- c# - 如果应用程序使用任务管理器关闭,c# 表单关闭事件会起作用吗?
- linux - 未找到清除命令 - Yocto core-image-base