SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
A deep dive into writing
NET Core Plugins
for NodeJS
Raffaele Rialdi Senior Software Architect
Vevy Europe
@raffaeler
raffaeler@vevy.com
Who am I?
• I am Raffaele Rialdi, Senior Software Architect in Vevy Europe – Italy
• I am also consultant in many industries (manufacturing, racing, healthcare, financial, …)
• But also Speaker in italian and international conferences, and Trainer as well
• And very proud to have been awarded as a Microsoft MVP since 2003
@raffaeler
raffaeler@vevy.com
github.com/raffaeler
Node.JS and V8
• Node.js® is a well-known runtime environment for javascript
• It leverages the power of "V8", the engine of Google Chrome
• V8 conforms to the ECMAScript 262 standard and runs cross-platforms
• NodeJs has a vivid ecosystem with tons of 3rd party libraries
• V8 can be extended with native addons (C++):
• When you need more performance
• To access operating system's resources and services
• To interoperate with external systems / hardware
https://nodejs.org
The basic structure
of a C++ V8 addon
• Including the libraries
• Declare the Entry-Point using
the NODE_MODULE macro
• Implement the entry-point and
declare javascript-friendly
methods
• The "Method" will be available
as "hello" to javascript
#include <node.h>
#include <v8.h>
NODE_MODULE(addon, init)
void init(Local<Object> exports)
{
NODE_SET_METHOD(exports, "hello", Method);
}
void Method(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(
String::NewFromUtf8(isolate, "world"));
}
// javascript code
const addon = require('./myAddon');
console.log(addon.hello()); // 'world'
The toolchain
• Bulding the addon requires a C++ toolchain
• Python, GCC for Linux, GCC / Xcode on Mac, VC++ on Windows
• The node-gyp tool
• Avoid the mess to manually download the node libraries and include files
• Abstracts the build operation from the mentioned toolchains
• Instead of creating a 'makefile' there is a 'binding.gyp' file
npm install -g node-gyp
{
"targets": [
{
"target_name": "myaddon",
"sources": [ "src/myaddon.cpp" ]
} ] }
npm config set msvs_version 2015
configuring gyp to use VC++2015 toolchain
V8 Object Wrapping
• By deriving the ObjectWrap class, we can expose objects to JS
• At initialization time, we define the members of the object
• Constructors, methods, properties, indexers
• We "set" the exports with the class name and the template declaring the
members
• All member handlers are static void functions
• Receive a "const FunctionCallbackInfo<Value>& args"
• Don't forget javascript is dynamic. The args contain the runtime values of the arguments
• Retrieve the context of the wrapper instance using ObjectWrap:Unwrap
• Set the return value using "args.GetReturnValue().Set(…);"
exports->Set(v8className, constructorTemplate->GetFunction());
V8 Type System and marshalling
• The V8 type system is different from the C++ types
• This is because V8 types are managed through the Garbage Collector
• Marshalling is needed to copy from/to C++ types
• There more V8 types than expected
• Int32, Number, String, Boolean, Function, Object, Function, …
• Strings are UTF8 while .NET use UTF16. Both are needed.
static std::string FromV8String(const Local<Value>& value)
{
String::Utf8Value utf8(value);
std::string str(*utf8);
return str;
}
static std::wstring FromV8StringW(const Local<Value>& value)
{
String::Utf8Value utf8(value);
auto str = raf_helpers::Helpers::utf8_to_wstring(*utf8);
return str;
}
Threading and the libuv threading library
• It is the library used by NodeJs and V8 to manage threads
• The JS code must be always executed in the main thread
• Javascript callbacks are often needed for time-expensive
methods
• When a .NET method signature return a Task the result must be
marshalled back to the main thread
• The libuv library give a very basic support for enqueuing
messages in its threads
• Every execution coming from another thread must be queued
back to the main thread
Demo: a simple V8 plugin
Hosting the CoreCLR
• What does it mean hosting the CLR?
• A native (C++) application can load the CLR, some assemblies and run
managed code
• SQL Server is a great example of native application hosting the CLR
• You can do it too!
• The CLR in .NET Framework could be hosted only on Windows
• It is based on the COM infrastructure
• The new Net Core can be hosted as well but cross-platform
• It mimics the COM interfaces, but the infrastructure is not COM-dependent
Hosting the CLR
• Including the libraries
• Load the coreclr.dll
• Get the entrypoint
• Get the RuntimeHost
• Start the CLR
• Create the AppDomain
#include <mscoree.h>
auto loader = LoadLibrary(fullCoreClr.c_str());
auto prhf = (FnGetCLRRuntimeHost)::GetProcAddress(
(HMODULE)loader, "GetCLRRuntimeHost");
ICLRRuntimeHost2* prh = nullptr;
hr = prhf(IID_ICLRRuntimeHost2, (IUnknown**)&prh);
prh->Authenticate(CORECLR_HOST_AUTHENTICATION_KEY);
hr = prh->Start();
hr = prh->CreateAppDomainWithManager(…)
Demo: loading the CLR
.NET Code
Introducing xcore
Javascript / Typescript code
xcorexcore C++ xcore .NET
.NET Core
V8
Why xcore?
• C++ can only call static .NET methods
• There is no semantics for the object lifecycle, properties, events and async
• xcore analyze and caches.NET metadata
• Generates optimized code to access each object's instance
• Expression Trees are then compiled and delegates are cached
• Object Instances are maintained and tied to the JS garbage collector
• The Marshalling code is optimized
• What about the graphs
• Every time a child object is accessed, xcore dynamically load metadata
xcore in action
• Load and initialize xcore
• Load the .net metadata
• Just the first needed class
• Create an instance
• Call methods
• Walk the graph
• new metadata is
loaded automatically
• Asynchronous calls
(and much more!)
var xcore = require('bindings')('xcore');
xcore.initialize(__dirname + "Sample",
"SampleLibrary.dll", "SampleLibrary.Initializer");
xcore.loadClass("SampleLibrary.OrderSample.
OrderManager, SampleLibrary");
var om = new xcore.OrderManager("raf");
console.log(om.Add("Hello, ", "world"));
console.log(om.SelectedOrder.Name);
om.AddAsync(2, 3, function(res){
console.log(res);
});
Performance profile
• There are still many improvements that can be done
• The add use-case is not realistic
• it just measure the xcore infrastructure and marshalling time
• xcore must marshal 4 times: (JS  C++  .NET  C++  JS)
1 Million calls
js: 6.156 ms
c++: 56.352 ms
.net: 1294.254 ms
console.time("net");
for(var i=0; i<loop; i++)
{
om.NetAdd(i, i);
}
console.timeEnd("net");
console.time("c++");
for(var i=0; i<loop; i++)
{
xcore.add(i, i);
}
console.timeEnd("c++");
console.time("js");
for(var i=0; i<loop; i++)
{
LocalAdd(i, i);
}
console.timeEnd("js");
js: 6.156ms c++: 56.352ms .net: 1294.254ms
var om = new xcore.OrderManager();
om.Add(2, 2); // jitting
LocalAdd(2,2); // jitting
xcore.add(2, 2); // jitting
var loop = 1000000; // 1 Million
function LocalAdd(x, y)
{ return x + y; }
prepare the benchmark local javascript C++ only xcore + C#
Use-cases
1. Node.js applications
2. UI created with the Electron framework
• Ability to create .NET ViewModels for Angular (by Google)
3. Using JS to script Windows Powershell
4. Nativescript Mobile applications
• Nativescript is a project by Progress Software Corporation
https://www.nativescript.org/
5. Anything else based on V8
http://electron.atom.io
Join me at the Exhibition zone
• xcore in action
• Raspberry PI running netcore (and more)
@raffaeler
Questions?
www.iamraf.net
raffaeler@vevy.com
Raffaele Rialdi

Weitere ähnliche Inhalte

Was ist angesagt?

BlaBlaCar and infrastructure automation
BlaBlaCar and infrastructure automationBlaBlaCar and infrastructure automation
BlaBlaCar and infrastructure automation
sinfomicien
 
DCSF 19 Modernizing Insurance with Docker Enterprise: The Physicians Mutual ...
DCSF 19 Modernizing Insurance with Docker Enterprise:  The Physicians Mutual ...DCSF 19 Modernizing Insurance with Docker Enterprise:  The Physicians Mutual ...
DCSF 19 Modernizing Insurance with Docker Enterprise: The Physicians Mutual ...
Docker, Inc.
 

Was ist angesagt? (20)

Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn't suck - Tomer Gabel, WixNashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
 
Ansible Introduction
Ansible Introduction Ansible Introduction
Ansible Introduction
 
Learning chef
Learning chefLearning chef
Learning chef
 
Performance Testing using Real Browsers with JMeter & Webdriver
Performance Testing using Real Browsers with JMeter & WebdriverPerformance Testing using Real Browsers with JMeter & Webdriver
Performance Testing using Real Browsers with JMeter & Webdriver
 
Continuous Delivery and Infrastructure as Code
Continuous Delivery and Infrastructure as CodeContinuous Delivery and Infrastructure as Code
Continuous Delivery and Infrastructure as Code
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLEverything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPL
 
"Using Automation Tools To Deploy And Operate Applications In Real World Scen...
"Using Automation Tools To Deploy And Operate Applications In Real World Scen..."Using Automation Tools To Deploy And Operate Applications In Real World Scen...
"Using Automation Tools To Deploy And Operate Applications In Real World Scen...
 
DevOps Toolbox: Infrastructure as code
DevOps Toolbox: Infrastructure as codeDevOps Toolbox: Infrastructure as code
DevOps Toolbox: Infrastructure as code
 
AWS Developer Fundamentals
AWS Developer FundamentalsAWS Developer Fundamentals
AWS Developer Fundamentals
 
Immutable Infrastructure: the new App Deployment
Immutable Infrastructure: the new App DeploymentImmutable Infrastructure: the new App Deployment
Immutable Infrastructure: the new App Deployment
 
Automated Deployment with Capistrano
Automated Deployment with CapistranoAutomated Deployment with Capistrano
Automated Deployment with Capistrano
 
Continuous Delivery With Selenium Grid And Docker
Continuous Delivery With Selenium Grid And DockerContinuous Delivery With Selenium Grid And Docker
Continuous Delivery With Selenium Grid And Docker
 
Rock Solid Deployment of Web Applications
Rock Solid Deployment of Web ApplicationsRock Solid Deployment of Web Applications
Rock Solid Deployment of Web Applications
 
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and MesosIguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
 
BlaBlaCar and infrastructure automation
BlaBlaCar and infrastructure automationBlaBlaCar and infrastructure automation
BlaBlaCar and infrastructure automation
 
Your journey into the serverless world
Your journey into the serverless worldYour journey into the serverless world
Your journey into the serverless world
 
Dockerize Laravel Application
Dockerize Laravel ApplicationDockerize Laravel Application
Dockerize Laravel Application
 
A tale of two pizzas: Developer tools at AWS
A tale of two pizzas: Developer tools at AWSA tale of two pizzas: Developer tools at AWS
A tale of two pizzas: Developer tools at AWS
 
DCSF 19 Modernizing Insurance with Docker Enterprise: The Physicians Mutual ...
DCSF 19 Modernizing Insurance with Docker Enterprise:  The Physicians Mutual ...DCSF 19 Modernizing Insurance with Docker Enterprise:  The Physicians Mutual ...
DCSF 19 Modernizing Insurance with Docker Enterprise: The Physicians Mutual ...
 
WinOps Conf 2016 - Jeffrey Snover - The DevOpsification of Windows Server
WinOps Conf 2016 - Jeffrey Snover - The DevOpsification of Windows ServerWinOps Conf 2016 - Jeffrey Snover - The DevOpsification of Windows Server
WinOps Conf 2016 - Jeffrey Snover - The DevOpsification of Windows Server
 

Ähnlich wie Raffaele Rialdi

Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
DataArt
 
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvpZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
Chalermpon Areepong
 

Ähnlich wie Raffaele Rialdi (20)

Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript Engine
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Everything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureEverything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventure
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application Framework
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Monitoring Docker at Scale - Docker San Francisco Meetup - August 11, 2015
Monitoring Docker at Scale - Docker San Francisco Meetup - August 11, 2015Monitoring Docker at Scale - Docker San Francisco Meetup - August 11, 2015
Monitoring Docker at Scale - Docker San Francisco Meetup - August 11, 2015
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvpZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentation
 

Mehr von CodeFest

Mehr von CodeFest (20)

Alexander Graebe
Alexander GraebeAlexander Graebe
Alexander Graebe
 
Никита Прокопов
Никита ПрокоповНикита Прокопов
Никита Прокопов
 
Денис Баталов
Денис БаталовДенис Баталов
Денис Баталов
 
Елена Гальцина
Елена ГальцинаЕлена Гальцина
Елена Гальцина
 
Александр Калашников
Александр КалашниковАлександр Калашников
Александр Калашников
 
Ирина Иванова
Ирина ИвановаИрина Иванова
Ирина Иванова
 
Marko Berković
Marko BerkovićMarko Berković
Marko Berković
 
Денис Кортунов
Денис КортуновДенис Кортунов
Денис Кортунов
 
Александр Зимин
Александр ЗиминАлександр Зимин
Александр Зимин
 
Сергей Крапивенский
Сергей КрапивенскийСергей Крапивенский
Сергей Крапивенский
 
Сергей Игнатов
Сергей ИгнатовСергей Игнатов
Сергей Игнатов
 
Николай Крапивный
Николай КрапивныйНиколай Крапивный
Николай Крапивный
 
Alexander Graebe
Alexander GraebeAlexander Graebe
Alexander Graebe
 
Вадим Смирнов
Вадим СмирновВадим Смирнов
Вадим Смирнов
 
Константин Осипов
Константин ОсиповКонстантин Осипов
Константин Осипов
 
Максим Пугачев
Максим ПугачевМаксим Пугачев
Максим Пугачев
 
Rene Groeschke
Rene GroeschkeRene Groeschke
Rene Groeschke
 
Иван Бондаренко
Иван БондаренкоИван Бондаренко
Иван Бондаренко
 
Mete Atamel
Mete AtamelMete Atamel
Mete Atamel
 
Алексей Акулович
Алексей АкуловичАлексей Акулович
Алексей Акулович
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Raffaele Rialdi

  • 1. A deep dive into writing NET Core Plugins for NodeJS Raffaele Rialdi Senior Software Architect Vevy Europe @raffaeler raffaeler@vevy.com
  • 2. Who am I? • I am Raffaele Rialdi, Senior Software Architect in Vevy Europe – Italy • I am also consultant in many industries (manufacturing, racing, healthcare, financial, …) • But also Speaker in italian and international conferences, and Trainer as well • And very proud to have been awarded as a Microsoft MVP since 2003 @raffaeler raffaeler@vevy.com github.com/raffaeler
  • 3. Node.JS and V8 • Node.js® is a well-known runtime environment for javascript • It leverages the power of "V8", the engine of Google Chrome • V8 conforms to the ECMAScript 262 standard and runs cross-platforms • NodeJs has a vivid ecosystem with tons of 3rd party libraries • V8 can be extended with native addons (C++): • When you need more performance • To access operating system's resources and services • To interoperate with external systems / hardware https://nodejs.org
  • 4. The basic structure of a C++ V8 addon • Including the libraries • Declare the Entry-Point using the NODE_MODULE macro • Implement the entry-point and declare javascript-friendly methods • The "Method" will be available as "hello" to javascript #include <node.h> #include <v8.h> NODE_MODULE(addon, init) void init(Local<Object> exports) { NODE_SET_METHOD(exports, "hello", Method); } void Method(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set( String::NewFromUtf8(isolate, "world")); } // javascript code const addon = require('./myAddon'); console.log(addon.hello()); // 'world'
  • 5. The toolchain • Bulding the addon requires a C++ toolchain • Python, GCC for Linux, GCC / Xcode on Mac, VC++ on Windows • The node-gyp tool • Avoid the mess to manually download the node libraries and include files • Abstracts the build operation from the mentioned toolchains • Instead of creating a 'makefile' there is a 'binding.gyp' file npm install -g node-gyp { "targets": [ { "target_name": "myaddon", "sources": [ "src/myaddon.cpp" ] } ] } npm config set msvs_version 2015 configuring gyp to use VC++2015 toolchain
  • 6. V8 Object Wrapping • By deriving the ObjectWrap class, we can expose objects to JS • At initialization time, we define the members of the object • Constructors, methods, properties, indexers • We "set" the exports with the class name and the template declaring the members • All member handlers are static void functions • Receive a "const FunctionCallbackInfo<Value>& args" • Don't forget javascript is dynamic. The args contain the runtime values of the arguments • Retrieve the context of the wrapper instance using ObjectWrap:Unwrap • Set the return value using "args.GetReturnValue().Set(…);" exports->Set(v8className, constructorTemplate->GetFunction());
  • 7. V8 Type System and marshalling • The V8 type system is different from the C++ types • This is because V8 types are managed through the Garbage Collector • Marshalling is needed to copy from/to C++ types • There more V8 types than expected • Int32, Number, String, Boolean, Function, Object, Function, … • Strings are UTF8 while .NET use UTF16. Both are needed. static std::string FromV8String(const Local<Value>& value) { String::Utf8Value utf8(value); std::string str(*utf8); return str; } static std::wstring FromV8StringW(const Local<Value>& value) { String::Utf8Value utf8(value); auto str = raf_helpers::Helpers::utf8_to_wstring(*utf8); return str; }
  • 8. Threading and the libuv threading library • It is the library used by NodeJs and V8 to manage threads • The JS code must be always executed in the main thread • Javascript callbacks are often needed for time-expensive methods • When a .NET method signature return a Task the result must be marshalled back to the main thread • The libuv library give a very basic support for enqueuing messages in its threads • Every execution coming from another thread must be queued back to the main thread
  • 9. Demo: a simple V8 plugin
  • 10. Hosting the CoreCLR • What does it mean hosting the CLR? • A native (C++) application can load the CLR, some assemblies and run managed code • SQL Server is a great example of native application hosting the CLR • You can do it too! • The CLR in .NET Framework could be hosted only on Windows • It is based on the COM infrastructure • The new Net Core can be hosted as well but cross-platform • It mimics the COM interfaces, but the infrastructure is not COM-dependent
  • 11. Hosting the CLR • Including the libraries • Load the coreclr.dll • Get the entrypoint • Get the RuntimeHost • Start the CLR • Create the AppDomain #include <mscoree.h> auto loader = LoadLibrary(fullCoreClr.c_str()); auto prhf = (FnGetCLRRuntimeHost)::GetProcAddress( (HMODULE)loader, "GetCLRRuntimeHost"); ICLRRuntimeHost2* prh = nullptr; hr = prhf(IID_ICLRRuntimeHost2, (IUnknown**)&prh); prh->Authenticate(CORECLR_HOST_AUTHENTICATION_KEY); hr = prh->Start(); hr = prh->CreateAppDomainWithManager(…)
  • 13. .NET Code Introducing xcore Javascript / Typescript code xcorexcore C++ xcore .NET .NET Core V8
  • 14. Why xcore? • C++ can only call static .NET methods • There is no semantics for the object lifecycle, properties, events and async • xcore analyze and caches.NET metadata • Generates optimized code to access each object's instance • Expression Trees are then compiled and delegates are cached • Object Instances are maintained and tied to the JS garbage collector • The Marshalling code is optimized • What about the graphs • Every time a child object is accessed, xcore dynamically load metadata
  • 15. xcore in action • Load and initialize xcore • Load the .net metadata • Just the first needed class • Create an instance • Call methods • Walk the graph • new metadata is loaded automatically • Asynchronous calls (and much more!) var xcore = require('bindings')('xcore'); xcore.initialize(__dirname + "Sample", "SampleLibrary.dll", "SampleLibrary.Initializer"); xcore.loadClass("SampleLibrary.OrderSample. OrderManager, SampleLibrary"); var om = new xcore.OrderManager("raf"); console.log(om.Add("Hello, ", "world")); console.log(om.SelectedOrder.Name); om.AddAsync(2, 3, function(res){ console.log(res); });
  • 16. Performance profile • There are still many improvements that can be done • The add use-case is not realistic • it just measure the xcore infrastructure and marshalling time • xcore must marshal 4 times: (JS  C++  .NET  C++  JS) 1 Million calls js: 6.156 ms c++: 56.352 ms .net: 1294.254 ms console.time("net"); for(var i=0; i<loop; i++) { om.NetAdd(i, i); } console.timeEnd("net"); console.time("c++"); for(var i=0; i<loop; i++) { xcore.add(i, i); } console.timeEnd("c++"); console.time("js"); for(var i=0; i<loop; i++) { LocalAdd(i, i); } console.timeEnd("js"); js: 6.156ms c++: 56.352ms .net: 1294.254ms var om = new xcore.OrderManager(); om.Add(2, 2); // jitting LocalAdd(2,2); // jitting xcore.add(2, 2); // jitting var loop = 1000000; // 1 Million function LocalAdd(x, y) { return x + y; } prepare the benchmark local javascript C++ only xcore + C#
  • 17. Use-cases 1. Node.js applications 2. UI created with the Electron framework • Ability to create .NET ViewModels for Angular (by Google) 3. Using JS to script Windows Powershell 4. Nativescript Mobile applications • Nativescript is a project by Progress Software Corporation https://www.nativescript.org/ 5. Anything else based on V8 http://electron.atom.io
  • 18. Join me at the Exhibition zone • xcore in action • Raspberry PI running netcore (and more)