[Node.js] Node.js 透過edge 呼叫 DLL (C#) 的 function
2015-10-12
因為專案的一些因素,必須要透過Node.js 去呼叫 C# 的 Library ,測試了一下,所以記錄下來
1.必須透過一個 lib 叫做 edge.js
安裝指令
npm install edge
2. C# 部分 ,Namespace 是 TestNSLib ,主要的 Class 是 MainClass 我們設計一個 method 是 ToChangeUserData ,此method 必須傳入一個User 物件,傳出也是一個User 物件,但是Name 的Property 會加入 --Modified By C#
User Model :
public class User
{
public string Name { get; set; }
public int Age { get; set; }
/// <summary>
/// false:F , true:M
/// </summary>
public bool Gender { get; set; }
}
ToChangeUserData Method :
/// <summary>
/// 測試 傳入一個User 物件
///
/// </summary>
/// <param name="input">User 物件 來自 node.js 進來的物件 </param>
/// <returns>回傳 User 物件</returns>
public async Task<object> ToChangeUserData(dynamic input)
{
try
{
var user = new User
{
Name = (string)input.Name,
Age = (int)input.Age,
Gender = (bool)input.Gender
};
//將名稱改成後面加上Modified by C# 之後回傳物件
user.Name += "--Modified By C#";
return user;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "," + ex.StackTrace);
return null;
}
}
full code:
using System;
using System.Threading.Tasks;
namespace TestNSLib
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
/// <summary>
/// false:F , true:M
/// </summary>
public bool Gender { get; set; }
}
public partial class MainClass
{
/// <summary>
/// 測試 傳入一個User 物件
///
/// </summary>
/// <param name="input">User 物件 來自 node.js 進來的物件 </param>
/// <returns>回傳 User 物件</returns>
public async Task<object> ToChangeUserData(dynamic input)
{
try
{
var user = new User
{
Name = (string)input.Name,
Age = (int)input.Age,
Gender = (bool)input.Gender
};
//將名稱改成後面加上Modified by C# 之後回傳物件
user.Name += "--Modified By C#";
return user;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "," + ex.StackTrace);
return null;
}
}
}
}
3.編譯出來dll的部分,複製到你要執行node.js 的地方, 我的程式碼是放在 c:\tmp\CallDllSample
4.我們來看呼叫得部分
var http = require('http');
// 引入 edge 模組
var edge = require('edge');
var objDLL = edge.func({
assemblyFile: 'TestNSLib.dll',
typeName: 'TestNSLib.MainClass',
methodName: 'ToChangeUserData'
});
var user1={Name:"Donma 許",Age:20,Gender:true};
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var userR=objDLL(user1,true);
res.end('Call ToChangeUserData Rsult:'+userR.Name+","+ userR.Age +'\n');
}).listen(9996, "127.0.0.1");
執行 nodejs 指令
我是改寫官方範例,做一個簡單的http 輸出結果
打完收工,給需要的人參考一下。
參考文件:
http://tjanczuk.github.io/edge/#/
http://mcluck90.tumblr.com/post/89814519378/getting-started-with-edgejs
https://github.com/tjanczuk/edge
標籤:
.Net
,
C#
,
Javascript
,
Node.js
,
Visual Studio Code
-- Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer. 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力...