edge.js架起node.js和.net互操作桥梁

     今天要介绍的是edge.js这个github上刚兴起的开源项目,它可以让node.js和.net之间在in-process下互操作。.net版本在4.5及以上,因为.net4.5带来的Task,asyn,await关键字和node.js的Event模型正好匹配。如果你感兴趣的话,可以参见githubhttps://github.com/tjanczuk/edge 和Edge.js overview.

下面这幅图展示了edge.js在node.js和.net之间互操作的桥梁。Fun<object,Task<object>>表示输入为object类型,输出为Task<object>,后者对应node.js中的回调函数,前者则为.net方法输入参数。更多详情请参见github readme。

   edge.js interop model

   下面我们写个菲波基数作为demo尝鲜:完整项目寄宿在github:edge-demo。

var edge = require('edge');

 

var fib = edge.func({

    source: function() {/*

 

using System;

using System.Linq;

using System.Threading.Tasks;

 

public class Startup

{

public async Task<object> Invoke(object input)

{

int v = (int)input;

var fib = Fix<int, int>(f => x => x <= 1 ? 1 : f(x - 1) + f(x - 2));

return fib(v);

}

 

static Func<T, TResult> Fix<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> f)

{

return x => f(Fix(f))(x);

}

 

static Func<T1, T2, TResult> Fix<T1, T2, TResult>(Func<Func<T1, T2, TResult>, Func<T1, T2, TResult>> f)

{

return (x, y) => f(Fix(f))(x, y);

}

}

 

*/},

    references: ['System.Core.dll']

});

 

fib(5, function (error, result) {

    if (error) console.log(error);

    console.log(result);

});

 

var fibFromFile = edge.func(__dirname + "/fib.cs");

fibFromFile(5, function (error, result) {

    if (error) console.log(error);

    console.log(result);

});

 

var fibFromDll = edge.func({

    assemblyFile: 'edge.demo.dll',

    typeName: 'edge.demo.Startup',

    methodName: 'Invoke'

});

fibFromDll(5, function (error, result) {

    if (error) console.log(error);

    console.log(result);

});

效果:

image

这里分为3类调用,直接源码嵌入node.js和文件外置,以后编译后的dll,多的不用说,其实很简单,如果你和一样同样喜欢js和.net的话。

在当下node.js刚兴起,成型的框架还不够多,或者有时我们必须以c或者c++来完成node.js的本地扩展的时候,edge.js给我们提供了另一个可选的途径就是 强大的.net大家族。

你可能感兴趣的:(.net,node.js,edge.js)