Home > Web Front-end > JS Tutorial > node.js calls module example developed in C_node.js

node.js calls module example developed in C_node.js

WBOY
Release: 2016-05-16 15:51:34
Original
1222 people have browsed it

How to use C to interact with node. In the node program, if there is a large amount of data calculation, which is relatively slow to process, you can use C to process it, and then return it to the node through a callback (in the form of a callback). Let’s first review the orthodox method of developing native modules in C

#include <node.h> 
#include <v8.h> 
using namespace v8; 
 
// 这里是 hello 函数的 C++ 实现部分 
Handle<Value> Method(const Arguments& args) { 
 HandleScope scope; 
 return scope.Close(String::New("world")); 
} 
 
// 这里是模块的初始化函数,必须有 
void init(Handle<Object> exports) { 
 exports->Set(String::NewSymbol("hello"), 
   FunctionTemplate::New(Method)->GetFunction()); 
} 
 
// 这里定义本模块的名字和初始化函数 
NODE_MODULE(hello, init)
Copy after login

If this module is written in Node, it looks like this:

exports.hello = function() { 
 return 'world'; 
};


为了编译 C++ 这个模块,还需要一个 JSON 格式的 binding.gyp 文件,来定义编译的细节。 
{ 
 "targets": [ 
  { 
   "target_name": "hello", 
   "sources": [ "hello.cpp" ] 
  } 
 ] 
}

Copy after login

Execute node-gyp configure build to compile directly.

node test.js: 
var addon = require('./build/Release/hello'); 

console.log(addon.hello()); 
Copy after login

Output the result.

In this way, node can directly call programs written in C.

Explanation of the above program: In hello.cc, we first created a function Method, which returns a string of "hello, world", and then we created an init function as an initialization function , we called a function

Finally, we bind this module as: NODE_MODULE(hello, init)

It is pointed out on the official website that all node plug-ins must output an initialization function, which means that the following code must be in each module and has a fixed format.

void Initialize (Handle<Object> exports); 
NODE_MODULE(module_name, Initialize) 
Copy after login

The module_name must correspond to the target_name in binding.gyp.

After node-gyp configure build is compiled, a new build folder will be generated under the current file. By referencing the result of this build in test.js, we can call the program written in C.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template