Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to achieve type conversion between NodeJS and C++

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to achieve type conversion between NodeJS and C++". In daily operation, I believe many people have doubts about how to achieve type conversion between NodeJS and C++. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to achieve type conversion between NodeJS and C++". Next, please follow the editor to study!

Although there is a lot of documentation on how to use these API on the official Node.js website, passing data between JavaScript and C++ is very troublesome. C++ is a strongly typed language ("1024" is a string type rather than an integer type), and JavaScript always does some type conversion for us by default.

The basic types of JavaScript include String,Number,Boolean,null,undefined,V8 's use of class inheritance to define this type, these types inherit the Primitive class, and Primitive inherits Value,v8 also supports integers (including Int32 and Uint32), and all type definitions can be seen in the V8 type documentation, in addition to basic types, there are also Object,Array,Map and other type definitions.

The inheritance relationships of basic types are shown in the following figure:

In V8, all JavaScript values are placed in the Local object, which specifies the memory unit of the JavaScript runtime.

The following generation defines a value of type Number, where the isolate variable declared in the Test function represents the heap memory in the V8 virtual machine, which is needed when creating a new variable, and the next line of code declares a variable of type Number through isolate.

# include # include using namespace v8; void Test (const v8 vig FunctionalCallbackInfo & args) {Isolate* isolate = args.GetIsolate (); / / declare variable Local retval = v8::Number::New (isolate, 1000);} void init (Local exports, Local module) {NODE_SET_METHOD (exports, "getTestValue", Test);} NODE_MODULE (returnValue, init)

After looking at the V8 type API documentation, you will find that for the basic JavaScript type, there are only variable declarations and no variable assignments. At first, I thought it was very strange, but after thinking about it, I found it reasonable. The main reasons are as follows:

The basic type of JavaScript is an immutable type, variables all point to an immutable memory unit, var a = 10, then a points to a memory cell containing a value of 5, re-assigning a = 100, not changing the value of this memory unit, but making a point to another memory unit with a value of 100. If you declare that both variables xQuery y have a value of 10, they point to the same memory unit.

The parameters of the function are all values, not references. When calling C++ 's function in JavaScript, the value is copied every time if the parameter is a basic type. Changing the value of the parameter will not affect the original value.

Variables of basic types declared with Local are references to memory units, because it is impossible to change the value of the reference to point to another memory unit for * * reasons, so there is no reassignment of variables.

Data flows to C++-> JavaScript

The following demo defines some common JavaScript types, including basic types as well as Object, Array, and Fuction.

# include # include using namespace v8; void MyFunction (const v8 vig FunctionalCallbackInfo & args) {Isolate* isolate = args.GetIsolate (); args.GetReturnValue (). Set (String::NewFromUtf8 (isolate, "Hello World!"));} void Test (const v8 veveFunctionCallbackInfo & args) {Isolate* isolate = args.GetIsolate (); / Number type declaration Local retval = v8::Number::New (isolate, 1000) / String type declaration Local str = v8::String::NewFromUtf8 (isolate, "Hello World!"); / / Object type declaration Local obj = v8::Object::New (isolate); / / object assignment obj- > Set (v8::String::NewFromUtf8 (isolate, "arg1"), str); obj- > Set (v8::String::NewFromUtf8 (isolate, "arg2"), retval) / / Function type declaration and assignment Local tpl = v8::FunctionTemplate::New (isolate, MyFunction); Local fn = tpl- > GetFunction (); / / function name fn- > SetName (String::NewFromUtf8 (isolate, "theFunction")); obj- > Set (isolate, "arg3"), fn); / / Boolean type declaration Local flag = Boolean::New (isolate, true) Obj- > Set (String::NewFromUtf8 (isolate, "arg4"), flag); / / declaration of Array type Local arr = Array::New (isolate); / / Array assignment arr- > Set (0, Number::New (isolate, 1); arr- > Set (1, Number::New (isolate, 10)); arr- > Set (2, Number::New (isolate, 1000)); arr- > Set (3, Number::New (isolate, 1000)) Obj- > Set (String::NewFromUtf8 (isolate, "arg5"), arr); / / declaration of Undefined type Local und = Undefined (isolate); obj- > Set (String::NewFromUtf8 (isolate, "arg6"), und); / / declaration of null type Local null = Null (isolate); obj- > Set (String::NewFromUtf8 (isolate, "arg7"), null) / / the return value args.GetReturnValue () .Set (obj) returned to JavaScript call;} void init (Local exports, Local module) {NODE_SET_METHOD (exports, "getTestValue", Test);} NODE_MODULE (returnValue, init)

All addon require an initialization function, such as the following code:

Void Initialize (Local exports)

NODE_MODULE (module_name, Initialize)

Initialize is the initialization function, module_name is the compiled binary file name, and the module name of the above code is returnValue.

After the above code has been compiled by node-gyp (the official document of the compilation process Candlestick + Addons is described in detail), it can be called in the following way.

/ / returnValue.node is the file generated after compilation, and the file name is determined by NODE_MODULE (returnValue, init).

Const returnValue = require ('. / build/Release/returnValue.node')

Console.log (returnValue.getTestValue ())

The running results are as follows:

Data flow to javaScript-> C++

The above demo shows how to define the JavaScript type in C++. The data flows from C++ to JavaScript, and in turn, the data needs to flow from javaScript to JavaScript, that is, some parameters need to be passed when calling C++ function.

The following code shows the process of determining the number of parameters, determining the parameter type, and converting the parameter type to V8, including the basic type as well as Object, Array, Fuction.

# include # include # include using namespace v8; using namespace std; void GetArgument (const FunctionCallbackInfo& args) {Isolate* isolate = args.GetIsolate (); / / Parameter length judgment if (args.Length ())

< 2) { isolate->

ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Wrong number of arguments")); return;} / / Parameter type determination if (! args [0]-> IsNumber () | |! args [1]-> IsNumber ()) {/ / throw error isolate- > ThrowException (String::NewFromUtf8 (isolate, "argumnets must be number")) } if (! args [0]-> IsObject ()) {printf ("I am not Object\ n");} if (! args [0]-> IsBoolean ()) {printf ("I am not Boolean\ n");} if (! args [0]-> IsArray ()) {printf ("I am not Array\ n") } if (! args [0]-> IsString ()) {printf ("I am not String\ n");} if (! args [0]-> IsFunction ()) {printf ("I am not Function\ n");} if (! args [0]-> IsNull ()) {printf ("I am not Null\ n") } if (! args [0]-> IsUndefined ()) {printf ("I am not Undefined\ n");} / / js Number type converted to v8 Number type Local value1 = Local::Cast (args [0]); Local value2 = Local::Cast (args [1]); double value = value1- > NumberValue () + value2- > NumberValue () / / convert js String type to v8 String type Local str = Local::Cast (args [2]); String::Utf8Value utfValue (str); coutGet (1)-> NumberValue (); / / convert js Object type to v8 Object type Local obj = Local::Cast (args [4]); / / get the value in the object according to key Local a = obj- > Get (String::NewFromUtf8 (isolate, "a")) Local b = obj- > Get (String::NewFromUtf8 (isolate, "b")); / / conversion of js Array type to v8 Array type Local c = Local::Cast (obj- > Get (String::NewFromUtf8 (isolate, "c"); coutGet (2)); String::Utf8Value utfValueD (cString); cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report