You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中调用C++函数及解决node-gyp依赖报错

Hey there! Let's work through your Node.js + C++ native module problem together—we'll cover why Python is required, fix the node-gyp errors, and correct the bugs in your code so everything runs smoothly.


一、Why does node-gyp need Python?

Even though your module logic is written in C++, node-gyp (Node.js's official tool for compiling native modules) relies on Python under the hood. Its core build scripts are written in Python, and it uses Python to handle configuration parsing, dependency resolution, and orchestrating the C++ compilation process. You'll need a compatible Python version (3.7–3.10 works best; newer versions may have compatibility issues) to get it working.


二、Fixing the "Python not found" error

  1. Install a compatible Python version: Grab Python 3.8 or 3.9 (this range has the best node-gyp support). On Windows, make sure to check the Add Python to PATH box during installation.
  2. Tell npm where to find Python: If the error persists after installation, manually set the Python path:
    • Windows: npm config set python C:\PythonXX\python.exe (replace XX with your version number, e.g., 38)
    • Linux/macOS: npm config set python /usr/bin/python3.8
  3. Verify the config: Run npm config get python to confirm the path points to your installed Python.

三、Fixing bugs in your code

Your code has several syntax and logic errors that will cause compilation or runtime failures. Here's the corrected version of each file:

1. binding.gyp (syntax fix)

The include_dirs command was missing closing quotes and parentheses:

{
  "targets": [{
    "target_name": "testlib",
    "sources": ["testlib.cpp", "testworker.cpp"],
    "include_dirs": ["<!(node -e \"require('nan')\")"]
  }]
}

2. testlib.cpp (spelling & macro fixes)

  • Fixed function name spelling inconsistencies
  • Corrected the module registration macro (NODU_MODULE → NODE_MODULE)
#include <nan.h>
#include "testworker.h"

NAN_METHOD(addThousandToNumber) {
  auto number = Nan::To<int>(info[0]).FromJust();
  auto *callback = new Nan::Callback(info[1].As<v8::Function>());
  Nan::AsyncQueueWorker(new TestWorker(number, callback));
}

NAN_MODULE_INIT(init) {
  Nan::SetMethod(target, "addThousandToNumber", addThousandToNumber);
}

NODE_MODULE(testlib, init);

3. testworker.h (syntax fixes)

  • Removed unnecessary delete callback (the parent AsyncWorker class manages this)
  • Added missing semicolons
#include <nan.h>

class TestWorker : public Nan::AsyncWorker {
public:
  TestWorker(int number, Nan::Callback *callback) 
    : Nan::AsyncWorker(callback), myNumber(number), myCallback(callback) {}
  
  ~TestWorker() {}
  
  void Execute();
  void HandleOKCallback();

private:
  int myNumber;
  Nan::Callback *myCallback;
};

4. testworker.cpp (variable case fix)

Corrected the variable name mismatch (numberJS → NumberJS):

#include "testworker.h"

void TestWorker::Execute() {
  for (int i = 0; i < 1000; i++) {
    myNumber++;
  }
}

void TestWorker::HandleOKCallback() {
  Nan::HandleScope scope;
  auto NumberJS = Nan::New(myNumber);
  v8::Local<v8::Value> argv[] = {Nan::Undefined(), NumberJS};
  myCallback->Call(2, argv);
}

5. package.json (minor cleanup)

Set the correct main entry file and move node-gyp to dev dependencies:

{
  "name": "testlib",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "install": "node-gyp clean configure build"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "nan": "^2.14.1"
  },
  "devDependencies": {
    "node-gyp": "^7.0.0"
  }
}

四、Compile and test your module

  1. Install dependencies: Run npm install—this will trigger node-gyp to compile your C++ code into build/Release/testlib.node automatically.
  2. Run the test: Execute node index.js—you should see the output 1020 (20 + 1000) in your terminal.

内容的提问来源于stack exchange,提问作者ALEX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:48:12