首先,我们创建一个简单的 C++ 模块,在其中定义一个结构体,并在结构体中定义一个简单的函数。

test.h:

#ifndef TEST_H
#define TEST_H

struct TestStruct {
    int x;
    int y;
};

int add(int a, int b);

#endif

test.cpp:

#include "test.h"

int add(int a, int b) {
    return a + b;
}

现在,我们需要将这个模块与 Node.js 绑定起来,我们需要创建一个 binding.gyp 文件来进行配置。

binding.gyp:

{
  "targets": [
    {
      "target_name": "test",
      "sources": [ "test.cpp" ],
      "include_dirs": [ "." ],
      "cflags_cc": [ "-std=c++11" ],
      "defines": [ "NAPI_DISABLE_CPP_EXCEPTIONS" ],
      "conditions": [
        ["OS=='win'", {
          "defines": [ "_CRT_SECURE_NO_WARNINGS" ]
        }]
      ],
      "libraries": []
    }
  ]
}

在这个 binding.gyp 文件中,我们需要指定目标名称、源文件、包含目录、编译标志、宏定义、条件编译和链接库等信息。

接下来,我们需要在 Node.js 中加载这个模块,并使用其中的函数和结构体。

nodejs:

const addon = require('./build/Release/test.node');

const testStruct = new addon.TestStruct();
testStruct.x = 10;
testStruct.y = 20;

const result = addon.add(testStruct.x, testStruct.y);
console.log(result);

我们创建一个新的 TestStruct 实例,并将其传递给 add 函数,然后将结果打印到控制台

nodejs c++ 写模块要有cpp和h放结构体的helloworld同时写bindinggyp配置

原文地址: https://www.cveoy.top/t/topic/fJXi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录