First introduce the difference between using v8 API and using swig framework:
(1) The v8 API method is the native method provided by the official, with powerful and complete functions. The disadvantage is that you need to be familiar with the v8 API, which is more troublesome to write. It is strongly related to js and cannot easily support other scripting languages.
(2) swig is a third-party support, a powerful component development tool that supports generating C++ component packaging code for a variety of common scripting languages such as python, lua, js, etc. swig users only need to write C++ code and swig configuration files You can develop C++ components in various scripting languages without knowing the component development frameworks of various scripting languages. The disadvantage is that it does not support JavaScript callbacks, the documentation and demo code are incomplete, and there are not many users.
1. Pure JS to implement Node.js components
(1) Go to the helloworld directory and execute npm init to initialize package.json. Ignore the various options and leave them as defaults.
(2) Component implementation index.js, for example:
module.exports.Hello = function(name) { console.log('Hello ' + name); }
(3) Execute in the outer directory: npm install ./helloworld, helloworld is then installed in the node_modules directory.
(4) Write component usage code:
var m = require('helloworld'); m.Hello('zhangsan'); //输出: Hello zhangsan
2. Use v8 API to implement JS components - synchronous mode
(1) Write binding.gyp, eg:
{ "targets": [ { "target_name": "hello", "sources": [ "hello.cpp" ] } ] }
(2) Write the implementation of the component hello.cpp, eg:
#include <node.h> namespace cpphello { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void Foo(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World")); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "foo", Foo); } NODE_MODULE(cpphello, Init) }
(3) Compile component
node-gyp configure node-gyp build ./build/Release/目录下会生成hello.node模块。
(4) Write test js code
const m = require('./build/Release/hello') console.log(m.foo()); //输出 Hello World
(5) Add package.json for installation eg:
{ "name": "hello", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "node test.js" }, "author": "", "license": "ISC" }
(5) Install components to node_modules
Go to the superior directory of the component directory and execute: npm install ./helloc //Note: helloc is the component directory
The hello module will be installed in the node_modules directory in the current directory. The test code is written like this:
var m = require('hello'); console.log(m.foo());
3. Use v8 API to implement JS components - asynchronous mode
The above description is a synchronous component. foo() is a synchronous function, that is, the caller of the foo() function needs to wait for the foo() function to finish executing before proceeding. When the foo() function is an IO time-consuming operation, function, the asynchronous foo() function can reduce blocking waits and improve overall performance.
To implement asynchronous components, you only need to pay attention to the uv_queue_work API of libuv. When implementing the component, except for the main code hello.cpp and the component user code, other parts are consistent with the above three demos.
hello.cpp:
/* * Node.js cpp Addons demo: async call and call back. * gcc 4.8.2 * author:cswuyg * Date:2016.02.22 * */ #include <iostream> #include <node.h> #include <uv.h> #include <sstream> #include <unistd.h> #include <pthread.h> namespace cpphello { using v8::FunctionCallbackInfo; using v8::Function; using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; using v8::Exception; using v8::Persistent; using v8::HandleScope; using v8::Integer; using v8::String; // async task struct MyTask{ uv_work_t work; int a{0}; int b{0}; int output{0}; unsigned long long work_tid{0}; unsigned long long main_tid{0}; Persistent<Function> callback; }; // async function void query_async(uv_work_t* work) { MyTask* task = (MyTask*)work->data; task->output = task->a + task->b; task->work_tid = pthread_self(); usleep(1000 * 1000 * 1); // 1 second } // async complete callback void query_finish(uv_work_t* work, int status) { Isolate* isolate = Isolate::GetCurrent(); HandleScope handle_scope(isolate); MyTask* task = (MyTask*)work->data; const unsigned int argc = 3; std::stringstream stream; stream << task->main_tid; std::string main_tid_s{stream.str()}; stream.str(""); stream << task->work_tid; std::string work_tid_s{stream.str()}; Local<Value> argv[argc] = { Integer::New(isolate, task->output), String::NewFromUtf8(isolate, main_tid_s.c_str()), String::NewFromUtf8(isolate, work_tid_s.c_str()) }; Local<Function>::New(isolate, task->callback)->Call(isolate->GetCurrentContext()->Global(), argc, argv); task->callback.Reset(); delete task; } // async main void async_foo(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope handle_scope(isolate); if (args.Length() != 3) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments num : 3"))); return; } if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsFunction()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments error"))); return; } MyTask* my_task = new MyTask; my_task->a = args[0]->ToInteger()->Value(); my_task->b = args[1]->ToInteger()->Value(); my_task->callback.Reset(isolate, Local<Function>::Cast(args[2])); my_task->work.data = my_task; my_task->main_tid = pthread_self(); uv_loop_t *loop = uv_default_loop(); uv_queue_work(loop, &my_task->work, query_async, query_finish); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "foo", async_foo); } NODE_MODULE(cpphello, Init) }
The idea of asynchronous is very simple. To implement a work function, a completion function, and a structure that carries data for cross-thread transmission, just call uv_queue_work. The difficulty is familiarity with v8 data structure and API.
test.js
// test helloUV module 'use strict'; const m = require('helloUV') m.foo(1, 2, (a, b, c)=>{ console.log('finish job:' + a); console.log('main thread:' + b); console.log('work thread:' + c); }); /* output: finish job:3 main thread:139660941432640 work thread:139660876334848 */
4. swig-javascript implements Node.js components
Use swig framework to write Node.js components
(1) Write the implementation of the component: *.h and *.cpp
eg:
namespace a { class A{ public: int add(int a, int y); }; int add(int x, int y); }
(2) Write *.i, used to generate swig packaging cpp file
eg:
/* File : IExport.i */ %module my_mod %include "typemaps.i" %include "std_string.i" %include "std_vector.i" %{ #include "export.h" %} %apply int *OUTPUT { int *result, int* xx}; %apply std::string *OUTPUT { std::string* result, std::string* yy }; %apply std::string &OUTPUT { std::string& result }; %include "export.h" namespace std { %template(vectori) vector<int>; %template(vectorstr) vector<std::string>; };
The %apply above means that int* result, int* xx, std::string* result, std::string* yy, std::string& result in the code are output descriptions. This is a typemap, which is a replacement. .
If the pointer parameters in the C++ function parameters return a value (specified through OUTPUT in the *.i file), Swig will process them as the return value of the JS function. If there are multiple pointers, the return value of the JS function is list.
%template(vectori) vector
(3) Write binding.gyp for compilation using node-gyp
(4) Generate warpper cpp file. Pay attention to the v8 version information when generating, eg: swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5) Compile & test
The difficulty lies in the use of stl types and custom types. There are too few official documents in this regard.
swig - JavaScript encapsulation use of std::vector, std::string, see: My exercise, mainly focusing on the implementation of *.i files.
5. Others
When using v8 API to implement Node.js components, you can find similarities with implementing Lua components. Lua has a state machine and Node has Isolate.
When Node implements object export, it needs to implement a constructor, add a "member function" to it, and finally export the constructor as a class name. When Lua implements object export, it also needs to implement a factory function to create objects, and also needs to add "member functions" to the table. Finally, export the factory function.
Node’s js script has the new keyword, but Lua does not, so Lua only provides external object factories for creating objects, while Node can provide object factories or class encapsulation.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 English version
Recommended: Win version, supports code prompts!
