node. JS calls C # code

Source: Internet
Author: User

What if we want to invoke DLL libraries that have been written in C # in a project in node. js? Edge.js is a good choice in this case, Edge.js is an open source technology on GitHub that allows node. js and. NET core to call each other within the same process, and supports Windows,macos and Linux. Edge.js can be installed locally via NPM, address: https://www.npmjs.com/package/edge#windows, there is a detailed introduction to it, there are a lot of use, The following is a brief introduction to the use of this method to let node. js invoke the DLL library for C #.

1. Installing Edge.js

NPM Install Edge

2. How to use Edge.js

var clrmethod = edge.func ({    // / assembly DLL name    typeName: ',     // class name, if not specified, the default is to find the ' Startup ' class    MethodName: '    // Method Name, method must be func<object,task<object>> and async, if not specified, the ' Invoke ' method will be found by default });

3. Writing C # (NodeTest.dll)

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacenodetest{ Public classStartup { Public Asynctask<Object> Invoke (stringparameter) {            var_strresult ="The input is illegal"; if(!string. IsNullOrEmpty (parameter) && parameter. Contains (","))            {                varA =0; varb =0; if(int. TryParse (parameter. Split (',')[0], outA) &&int. TryParse (parameter. Split (',')[1], outb)) {_strresult= (A +b).                ToString (); }            }            return_strresult; }    }}

4. Node. JS Call DLL

First we write the Dotnetfunction.js file, which we use to load the DLL

Const EDGE = require (' Edge ') Const Path= Require (' path ') Const FS= Require (' FS ')varDllPath = Path.join (__dirname, ' Dotnetclass/nodetest/nodetest/bin/debug/nodetest.dll ')varDotnetfunction =NULLif(Fs.existssync (DllPath)) {//1. Use Defalut modeDotnetfunction =Edge.func (DllPath)}Else{Console.log (' DLL path does not exist ')}exports.add=function(parameter) {if(Dotnetfunction!==NULL) {         returnDotnetfunction (parameter,true)     } Else {         return' Dotnetfunction is null '     } }

Let's use the methods in the Nodedotnettest.js in the Dotnetfunction.js

Const DOTNET = require ('./dotnetfunction.js ')var stringadd = ' 1,6 'var result =  Dotnet.add (Stringadd) console.log (' result: ', result)

At the command line, enter

Node Nodedotnettest.js

Get results

Result:7

The above is a simple example of node. js using Edge.js to invoke C # DLLs. However, often encountered in the use of more complex situations, such as C # code is often registered some events, these events are triggered after the need to notify node. js to do some logical processing, which involves C # call node. js, in the edge.js C # call JS code function, But in C # code embedded JS code, and did not see how to call node in the specified method, so I feel inappropriate, perhaps I did not see, if there are small partners found please tell me to correct. I used the method is to create a new queue in C # code, the event is triggered to add messages to this queue, in node. js, we set a timer to continue to take the data from this queue, according to the data obtained for analysis and then logical processing, here is a small example of this method, called C # DLL, I will specify the corresponding assembly name, class name, and method name.

5. Writing C # code, message Class

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacenodetest{ Public classMessage {Staticqueue<string> _queue =Newqueue<string>();  Public Asynctask<Object> Init (stringparameter) {            if(_queue! =default(queue<string>))            {                 for(inti =0; I <Ten; i++) {_queue.                Enqueue (i.ToString ()); }                return "Success"; }            Else            {                return "fail"; }        }         Public Asynctask<Object> Get (stringparameter) {            if(_queue. Count () >0)            {                return_queue.            Dequeue (); }            Else            {                return string.            Empty; }        }    }}

6. Writing Dotnetfunction.js

Const EDGE = require (' Edge ') Const Path= Require (' path ') Const FS= Require (' FS ')varDllPath = Path.join (__dirname, ' Dotnetclass/nodetest/nodetest/bin/debug/nodetest.dll ')varDotnetfunction =NULLvarDotnetinitfunction =NULLif(Fs.existssync (DllPath)) {dotnetinitfunction=Edge.func ({assemblyfile:dllpath, typeName:' Nodetest.message ', MethodName:' Init '}) Dotnetfunction=Edge.func ({assemblyfile:dllpath, typeName:' Nodetest.message ', MethodName:' Get '    })}Else{Console.log (' DLL path does not exist ')}exports.init=function () {    if(Dotnetinitfunction!==NULL) {        returnDotnetinitfunction ("",true)    } Else {        return' Dotnetinitfunction is null '}}exports.getmessage=function () {    if(Dotnetfunction!==NULL) {        returnDotnetfunction ("",true)    } Else {        return' Dotnetfunctionis null '    }}

7. Writing Nodedotnettest.js

Const DOTNET = require ('./dotnetfunction.js ')var initresult = dotnet.init () console.log (' Init result: ', Initresult)varfunction  () {    var message =  Dotnet.getmessage ()    ifnull && message!== ') {        Console.log ( ' message: ', message)    100)

8. Command Line Input

Node Nodedotnettest.js

Get results

init Result:  successmessage:    0 Message: 1  message: 2message:  3message:  4message:  5message:  6message:  7 message:   8message:  9

As you can see, the message can be taken from the queue, and we can do the corresponding processing in node. js as long as we can get the message. The above is about edge.js some of the use of methods, hope to help everyone!

node. JS calls C # code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.