C/C++开发求素数的Nodejs插件

okgoes 2023-05-09 13:07:15
Categories: Tags:

使用C语言开发去素数的nodejs插件,c语言代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <node.h>
#include <stdlib.h>

namespace Prime {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Exception;
using v8::Number;

// void Method(const FunctionCallbackInfo<Value>& args) {
//  Isolate* isolate = args.GetIsolate();
//  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
// }
void Prime(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
int i,j,a,b;
//int result[2];
// 检查传入的参数的个数
if (args.Length() < 1) {
// 抛出一个错误并传回到 JavaScript
isolate->ThrowException(Exception::TypeError(
    String::NewFromUtf8(isolate, "参数的数量错误")));
return;
}

// 检查参数的类型
if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "参数错误")));
return;
}
//创建一个对象,用于存储素数
Local<Object> obj = Object::New(isolate);
  
a=0;
b=0;
//求素数
for(i=2;i<=args[0]->NumberValue();i++) {
for(j=2;j<i;j++) {
if(i%j==0)
a++;
}
if(a<1) {
obj->Set(Number::New(isolate, b), Number::New(isolate, i));
b++;
a=0;
else
a=0;
}
args.GetReturnValue().Set(obj);
}

void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "prime", Prime);
}

NODE_MODULE(addon, init)

}  // namespace demo

安装node-gyp

npm install -g node-gyp

创建node-gyp的软连接

ln -s /usr/local/node/bin/node-gyp /usr/bin

创建binding.gyp

1
2
3
4
5
6
7
8
{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}

编译编写的c语言

node-gyp configure

执行后生成build文件夹

node-gyp build

目录结构如下

1
2
3
4
5
6
7
8
9
10
11
build
├── addon.target.mk
├── binding.Makefile
├── config.gypi
├── Makefile
└── Release
    ├── addon.node
    └── obj.target
        ├── addon
        │   └── hello.o
        └── addon.node

编译完成,编写测试的index.js

1
2
3
4
5
const addon = require('./build/Release/addon');

console.log(addon.prime(200));
``````bash
node index.js

执行结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{ '0': 2,
  '1': 3,
  '2': 5,
  '3': 7,
  '4': 11,
  '5': 13,
  '6': 17,
  '7': 19,
  '8': 23,
  '9': 29,
  '10': 31,
  '11': 37,
  '12': 41,
  '13': 43,
  '14': 47,
  '15': 53,
  '16': 59,
  '17': 61,
  '18': 67,
  '19': 71,
  '20': 73,
  '21': 79,
  '22': 83,
  '23': 89,
  '24': 97,
  '25': 101,
  '26': 103,
  '27': 107,
  '28': 109,
  '29': 113,
  '30': 127,
  '31': 131,
  '32': 137,
  '33': 139,
  '34': 149,
  '35': 151,
  '36': 157,
  '37': 163,
  '38': 167,
  '39': 173,
  '40': 179,
  '41': 181,
  '42': 191,
  '43': 193,
  '44': 197,
  '45': 199 }