JS与C#的交互

背景:1. 为了最大限度复用我们自己之前写的C#库的功能

           2. 给我们的工具只提供了JS的流程(:<) ,组织忽悠其他人员C#难用,JS好用。

目前edge-js提供了强大的JS与CLR的交互能力,任何属于CLR的语言都可以与JS交互。其实edge-JS是edge编译出来的JS版,可以被JS用来和C#交互。之前我尝试用nodeJS(12.16.1)+VS2017+VS2015 BuildTools编译edge,老是报错就放弃了。后来被告知edge-js有编译好的对应node版本,就用上了。

效果:nodeJS项目成功与C#库交互,nodeJS的传给callback也能被正确调用。

环境:Win10 Pro 64bit , VS2017 , NodeJS12.16.1 (64bit)

业务流程:

     1. JS传 1和2 给C#

     2. C#计算传进来的1+2的和 ,即3

      3. C#调用JS的callback,把3传给JS

      4. JS的callback把传进来的结果+1,即4 ,再传回C#

      5. C#调用另一个functon把结果乘以2得到8,返回JS显示最终结果

实现步骤:

1. 创建一个简单的C# dll项目

NodeJS与C#项目要一致,这里都是64位,否则NodeJS报错,只显示error,没有详细信息,很难debug。

注:C# 选AnyCPU都不行。

2. 生成NodeJS项目,安装edge-js npm包

3. 编写方法给JS用.这部分代码是参考edge的How to: call Node.js from C# 写的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace calc
{
    public class Class1
    {
         public async Task<object> IAdd(dynamic input)
        {
            await Task.Delay(0);
            int a = (int)input.a;
            int b = (int)input.b;
            Func<dynamic, Task<object>> c = (Func<dynamic, Task<object>>)input.c;
            var rc=  await  c(a+b); //JS callback返回的结果
            System.Diagnostics.Debug.WriteLine("Result from JS callback is "+rc);
            return Add((int)rc);
        }
        public int Add(int rc)
        {
            return rc*2;
        }
    }
}

4. 编写JS代码。


var edgeJS = require('edge-js');

var iadd = edgeJS.func({
    assemblyFile: 'calc/calc/bin/x64/Debug/calc.dll',
    typeName: 'calc.Class1',
    methodName: 'IAdd' // This must be Func<object,Task<object>>
});
var input={a:1,
    b:2,
    c:function(data,callback){
        console.log("this function is called in c#, passed in param is : "+data);
        //100 is the result from JS to C# , C# could use it to do subsequent steps
        //callback( new Error("In case there is a error , Specifyin it end up with whole JS terminated"),data+1);//必须有2个参数。第一个参数代表error,表示JS里调用出错了,导致整个APP停止.
        callback( null,data+1);
    }};
iadd(input,function(err,result){
if (err) 
{
    console.log(err);
    return;
}
console.log("this result is returned from C# :"+result);
});

5. VS2017编译C#项目,VS Code运行NodeJS项目可以看到结果

参考:

C#调用NodeJS的callback是有要求的,原文如下。即必须是2个参数,第一是error对象,第二个是JS返回给C#的结果

其他参考

猜你喜欢

转载自blog.csdn.net/Marcus2006/article/details/104986130
今日推荐