Jint打包后大概2M左右,但有一些小bug,比如函数内的严格模式不生效
ClearScript大概30M左右
测试基于windows x64 控制台程序
<PackageReference Include="Microsoft.ClearScript.Core" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
using Microsoft.ClearScript.V8;
var api = new Api();
var engine = new V8ScriptEngine();
//将.net对象添加到引擎内,这个是全局变量,
engine.AddHostObject("__API", api);
//将.net类型添加到引擎内
engine.AddHostType("Console", typeof(Console));
engine.Execute("Console.WriteLine(__API.MyProperty);");
//js内部定义函数,c#调用
engine.Execute(@"
function add(a,b){
return a+b;
}
//定义一个常量
let API = __API;
");
Console.WriteLine($"调用add方法-->{engine.Invoke("add", 1, 2)}");
Console.WriteLine($"访问API属性1-->{engine.Evaluate("API.MyProperty")}");
Console.WriteLine($"访问API属性2-->{engine.Evaluate("API.NoProp")}");//没有属性不会报错
//js内部定义函数,传递c#自定义对象
engine.Execute(@"
function test(api){
return api.MyProperty + 99;
}
");
Console.WriteLine(engine.Invoke("test", api));
//js代理包装.net对象
var proxyCode = @"
function __proxyObject(inputObject) {
let proxy = new Proxy(inputObject, {
get(targetObj, propoty, receiver) {
if (!targetObj.hasOwnProperty(propoty)) {
throw new Error(`'${targetObj}' 未包含属性: '${propoty}' `)
}
return targetObj[propoty]
}
});
return proxy;
}
const API2 = new __proxyObject(__API);
";
engine.Execute(proxyCode);
//engine.Execute("API2.NoProp");//没有这个属性会报错
//严格模式,将会触发报错
// engine.Execute("fn test2(){let a = 1; let a = 2;}");
Console.Read();
public class Api()
{
public int MyProperty { get; set; }
}
标签:engine,__,Execute,Console,c#,Jint,API,new,ClearScript
From: https://www.cnblogs.com/trykle/p/18254836