Home Web Front-end JS Tutorial Use C/C to implement Node.js modules (1)_node.js

Use C/C to implement Node.js modules (1)_node.js

May 16, 2016 pm 04:35 PM
c c++ node.js module

A pitfall that occurred a long time ago - using Node.js to reconstruct NBUT's Online Judge, including the evaluation side, also had to be reconstructed. (As for when it will be completed, don’t worry about it, (/‵Д′)/~ ╧╧

In short, what we have to do now is actually to use C/C to implement the Node.js module.

Preparation

If a worker wants to do his job well, he must first~~play a rogue~~ and sharpen his tools.

node-gyp

First you need a node-gyp module.

At any corner, execute:

Copy code The code is as follows:

$ npm install node-gyp -g

After a series of blahblahs, you are installed.

Python

 Then you need a python environment.

Go to the official website to get one yourself.


Note: According to node-gyp's GitHub, please make sure your python version is between 2.5.0 and 3.0.0.

Compilation environment

Well, I’m just too lazy to write it down in detail. Please go to node-gyp to see the compiler requirements. And pour it well.

Getting Started

Let me just talk about the introductory Hello World on the official website.

Hello World

Please prepare a C file, for example, call it ~~sb.cc~~ hello.cc.

Then let’s go step by step, first create the header file and define the namespace:

Copy code The code is as follows:

#include
#include
using namespace v8;

Main function

Next we write a function whose return value is Handle.

Copy code The code is as follows:

Handle Hello(const Arguments& args)
{
//... Waiting to be written
}

Then let me briefly analyze these things:

Handle

You must have integrity as a human being. I would like to state in advance that I refer to it from here (@fool).


V8 uses the Handle type to host JavaScript objects. Similar to C's std::sharedpointer, assignments between Handle types directly pass object references, but the difference is that V8 uses its own GC to manage the object life cycle, rather than intelligent Commonly used reference counting for pointers.

JavaScript types have corresponding custom types in C, such as String, Integer, Object, Date, Array, etc., which strictly abide by the inheritance relationship in JavaScript. When using these types in C, you must use Handle management to use the GC to manage their life cycle instead of using the native stack and heap.

This so-called Value can be seen from the various inheritance relationships in the header file v8.h of the V8 engine. It is actually the base class of various objects in JavaScript.

After understanding this matter, we can roughly understand the meaning of the above function declaration, which is that we write a Hello function that returns an indefinite type value.


Note: We can only return specific types, namely String, Integer, etc. under the management of Handle.

Arguments

This is the parameter passed into this function. We all know that in Node.js, the number of parameters is random. When these parameters are passed into C, they are converted into objects of this Arguments type.

We will talk about the specific usage later. Here you just need to understand what this is. (Why are you so careful? Because the examples in the official Node.js documentation are discussed separately. I am just talking about the first Hello World example now (´థ౪థ)σ

Contribution

Then we started to add bricks and tiles. Just two simple sentences:

Copy code The code is as follows:

Handle Hello(const Arguments& args)
{
HandleScope scope;
Return scope.Close(String::New("world"));
}

What do these two sentences mean? The rough meaning is to return a string "world" in Node.js.

HandleScope

The same reference comes from here.


The life cycle of Handle is different from that of C smart pointers. It does not exist within the scope of C semantics (that is, the part surrounded by {}), but needs to be manually specified through HandleScope. HandleScope can only be allocated on the stack. After the HandleScope object is declared, the life cycle of the Handle created subsequently is managed by HandleScope. After the HandleScope object is destructed, the Handle managed by it will be judged by the GC whether to be recycled.

So, we have to declare this Scope when we need to manage its life cycle. Okay, so why doesn't our code look like this?

Copy code The code is as follows:

Handle Hello(const Arguments& args)
{
HandleScope scope;
Return String::New("world");
}

Because when the function returns, the scope will be destructed and the Handles it manages will also be recycled, so this String will become meaningless.

So V8 came up with a magical idea - the HandleScope::Close(Handle Value) function! The purpose of this function is to close this Scope and transfer the parameters inside to the previous Scope for management, that is, the Scope before entering this function.

So there is our previous code scope.Close(String::New("world"));.

String::New

 This String class corresponds to the native string class in Node.js. Inherited from Value class. Similar to this, there is also:

•Array
•Integer
•Boolean
•Object
•Date
•Number
•Function
•...

Some of these things are inherited from Value, and some are inherited twice. We won’t do much research here. You can look at the V8 code (at least the header files) or read this manual.

And what about this New? You can see it here. Just create a new String object.

At this point, we have completed the analysis of this main function.

Export object

Let’s review it. If we write it in Node.js, how do we export functions or objects?

Copy code The code is as follows:

exports.hello = function() {}

So, how do we do this in C?

Initialization function

First, we write an initialization function:

Copy code The code is as follows:

void init(Handle exports)
{
//...I am waiting to write about your sister! #゚Å゚)⊂彡☆))゚Д゚)・∵
}

This is a turtle butt! It doesn’t matter what the function name is, but the parameter passed in must be a Handle, which means we are going to export something on this product next.

Then, we write the exported stuff here:

Copy code The code is as follows:

void init(Handle exports)
{
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Hello)->GetFunction());
}

The general meaning is that, add a field called hello to this exports object, and the corresponding thing is a function, and this function is our dear Hello function.

To put it plainly in pseudo code:

Copy code The code is as follows:

void init(Handle exports)
{
exports.Set("hello", function hello);
}

Done!

 (It’s done, sister! Shut up (‘д‘⊂彡☆))Д´)

True·Export

This is the last step. We finally have to declare that this is the entrance to the export, so we add this line at the end of the code:
NODE_MODULE(hello, init)

Did you pay a nenny? ! What is this?

Don’t worry, this NODE_MODULE is a macro, which means that we use the init initialization function to export the things to be exported to hello. So where does this hello come from?

It comes from the file name! Yes, that's right, it comes from the file name. You don't need to declare it in advance, and you don't have to worry about not being able to use it. In short, whatever the name of your final compiled binary file is, fill in the hello here, except for the suffix of course.

See the official documentation for details.


Note that all Node addons must export an initialization function:

Copy code The code is as follows:

void Initialize (Handle exports);
NODE_MODULE(module_name, Initialize)

There is no semi-colon after NODE_MODULE as it's not a function (see node.h).

The module_name needs to match the filename of the final binary (minus the .node suffix).

Compile (๑•́ ₃ •̀๑)

Come on, let’s compile it together!

Let’s create a new archive file similar to Makefile - binding.gyp.

 And add this code inside:

Copy code The code is as follows:

{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}

Why do you write it like this? You can refer to the official documentation of node-gyp.

configure

After the file is ready, we need to execute this command in this directory:

Copy code The code is as follows:

$ node-gyp configure

If everything is normal, a build directory should be generated, and there will be related files in it, maybe M$ Visual Studio's vcxproj file, etc., maybe Makefile, depending on the platform.

build

After the Makefile is generated, we start constructing and compiling:
$ node-gyp build

When everything is compiled, it is truly done! If you don’t believe me, take a look at the build/Release directory. Is there a hello.node file below? Yes, this is the soap that C will pick up for Node.js later!

Get gay! Node ヽ(✿゚▽゚)ノ C

We create a new file jianfeizao.js in the directory just now:

Copy code The code is as follows:

var addon = require("./build/Release/hello");
console.log(addon.hello());

Did you see it? Did you see it? It's out! It's out! The result of Node.js and C being radical! This addon.hello() is the Handle Hello(const Arguments& args) we wrote in the C code before, and we have now output the value it returns.

Go to sleep, the next section will be more in-depth

It’s getting late, so I’ll finish writing here today. By now, everyone can create the most basic C extension of Hello world. The next time I write it should be more in-depth. As for when the next time will be, I actually don’t know.
(Hey, hey, hey, how can a masturbator be so irresponsible! (o゚ロ゚)┌┛Σ(ノ´ω`)ノ

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Do you use c in visual studio code Do you use c in visual studio code Apr 15, 2025 pm 08:03 PM

Writing C in VS Code is not only feasible, but also efficient and elegant. The key is to install the excellent C/C extension, which provides functions such as code completion, syntax highlighting, and debugging. VS Code's debugging capabilities help you quickly locate bugs, while printf output is an old-fashioned but effective debugging method. In addition, when dynamic memory allocation, the return value should be checked and memory freed to prevent memory leaks, and debugging these issues is convenient in VS Code. Although VS Code cannot directly help with performance optimization, it provides a good development environment for easy analysis of code performance. Good programming habits, readability and maintainability are also crucial. Anyway, VS Code is

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

See all articles