A pitfall from N long ago - using Node.js to reconstruct NBUT's Online Judge, including the evaluation side, also needs to be reconstructed. (As for when it is completed, don't care, (/Д′)/~
In short, what we are going to do now is to use C/C++ to implement Node.js modules.
Preparation
If you want to do things well, you must first act like a gangster and sharpen your tools.
node-gyp
First you need a node-gyp module.
In any corner, execute:
The code copy is as follows:
$ npm install node-gyp -g
After a series of blahblahs, you have installed it.
Python
Then you need to have a python environment.
Go to the official website and get one.
Note: According to node-gyp's GitHub display, be sure to ensure that your python version is between 2.5.0 and 3.0.0.
Compilation environment
Well, I'm just lazy and not writing it in detail. Please move to node-gyp to see the compiler's needs. And make a fuss.
getting Started
I'll tell you about the introduction to the official website Hello World.
Hello World
Please prepare a C++ file, for example, it is called ~~sb.cc~~ hello.cc.
Then we will take a step by step, first create the header file and define the namespace:
The code copy is as follows:
#include <node.h>
#include <v8.h>
using namespace v8;
Main functions
Next we write a function whose return value is Handle<Value>.
The code copy is as follows:
Handle<Value> Hello(const Arguments& args)
{
//... Was hungry to be written
}
Then I will analyze these things roughly:
Handle<Value>
You must be honest in life. I declare 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, the assignments between Handle types are directly passed object references, but the difference is that V8 uses its own GC to manage the object life cycle, rather than the reference count commonly used by smart pointers.
JavaScript types have corresponding custom types in C++, such as String, Integer, Object, Date, Array, etc., and strictly abide by the inheritance relationship in JavaScript. When using these types in C++, you must use Handle hosting to use GC to manage their life cycles without using native stacks and heaps.
This so-called Value, which can be seen from the various inheritance relationships in the header file v8.h of the V8 engine, is actually the base class of various objects in JavaScript.
After understanding this, we can roughly understand the meaning of the above function statement, which means that we write a Hello function, which returns a value of an uncertain type.
Note: We can only return specific types, namely String, Integer, etc. under Handle hosting.
Arguments
This is the parameter to pass in 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 an Arguments type object.
Let’s talk about the specific usage later. Here we just need to understand what this is. (To keep it a secret? Because the examples in the official Node.js document are discussed separately. I am just talking about the first Hello World example ( ´థ౪థ) σ
Add bricks and tiles
Next we start to contribute. Just the simplest sentences:
The code copy is as follows:
Handle<Value> Hello(const Arguments& args)
{
HandleScope scope;
return scope.Close(String::New("world"));
}
What do these two sentences mean? The general meaning is to return a string "world" in Node.js.
HandleScope
The same reference is from here.
The life cycle of Handle is different from that of C++ smart pointers. It does not survive 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 Handle created later is managed by HandleScope. After the HandleScope object is destructed, the Handle managed by it will be determined by the GC.
So, we have to declare this Scope when we need to manage its life cycle. OK, so why don't our code be written like this?
The code copy is as follows:
Handle<Value> 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 be recycled, so this String will become meaningless.
So V8 came up with a magical idea - the HandleScope::Close(Handle<T> Value) function! The purpose of this function is to close the Scope and hand over the parameters inside to the previous Scope management, that is, the Scope before entering this function.
So we have the previous code scope.Close(String::New("world"));.
String::New
The String class corresponds to the native string class in Node.js. Inherited from the Value class. Similarly, there are:
•Array
•Integer
•Boolean
•Object
•Date
•Number
•Function
•...
Some of these things are inherited from Value, while others are inherited from secondary. We won't do much research here. You can look at the V8 code (at least the header file) or look at this manual.
And what about this New? You can see it here. It is to create a new String object.
At this point, we have finished parsing this main function.
Export Objects
Let’s review it. If it is written in Node.js, how do we export functions or objects?
The code copy is as follows:
exports.hello = function() {}
So, how can we do this in C++?
Initialize function
First, let's write an initialization function:
The code copy is as follows:
void init(Handle<Object> exports)
{
//... I'm hungry to write about your sister! #゚Å゚)⊂ち☆))゚Д゚)・∵
}
This is a turtle ass! It doesn't matter if the function name or something, but the passed parameter must be a Handle<Object>, which means that we will export things from this product below.
Then, we write the exported thing here:
The code copy is as follows:
void init(Handle<Object> exports)
{
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Hello)->GetFunction());
}
The general meaning is to 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 write a simple point in pseudo-code:
The code copy is as follows:
void init(Handle<Object> exports)
{
exports.Set("hello", function hello);
}
The work is done!
(Your sister is done! Shut up ('д'⊂☡☆))Д´)
True export
This is the last step, and we will finally declare that this is the entrance to the export, so we add this line at the end of the code:
NODE_MODULE(hello, init)
Have you taken a ni? ! 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 into hello. So where does this hello come from?
It comes from the file name! Yes, yes, 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, what is the name of your final compiled binary file? You will fill in the hello here, and of course you have to remove the suffix name.
See the official documentation for details.
Note that all Node adds must export an initialization function:
The code copy is as follows:
void Initialize (Handle<Object> 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 together!
Let's create a new archive file similar to Makefile - binding.gyp.
And add the code like this:
The code copy is as follows:
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}
Why write 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:
The code copy is as follows:
$ node-gyp configure
If everything is OK, a build directory should be generated, and then there are related files inside, maybe M$ Visual Studio vcxproj file, etc., or maybe Makefile, depending on the platform.
build
After the Makefile is generated, we start constructing and compiling:
$ node-gyp build
Only when everything is compiled will it be considered that the real task is completed! If you don’t believe it, go and check the build/Release directory. Is there a hello.node file below? That's right, this is the soap that C++ wants to pick up for Node.js later!
Let's get the basics! Node (✿゚゚)ノC++
We create a new file jianfeizao.js in the directory just now:
The code copy is as follows:
var addon = require("./build/Release/hello");
console.log(addon.hello());
See it or not! See it or not! Come out! The result of Node.js and C++ getting basics! This addon.hello() is the Handle<Value> Hello(const Arguments& args) we wrote in C++ code before, and we have now output the value it returns.
Take a shower and go to bed, and the next section is deeper
It's getting late, so I'll end up writing today. So far, everyone can come up with the most basic Hello world C++ extension. The next time I write it, I don’t know when the next time will be.
(Hey, hey, how can the master be so irresponsible! (o゚ロ?)┌┛Σ(ノ´ω`)ノ