jint 使用外部三方库的方法
jint 提供了clr 库的操作能力,使用方法有好几种,目前测试是对于系统内部的开启clr 之后是可以直接通过namespace 访问的,但是对于一些三方的需要明确下,以下简单说明下
内部clr 使用
- 开启alr 就可以了
return new Engine(options =>
{
options.ExperimentalFeatures=ExperimentalFeature.All;
options.AllowClr();
});
- 使用
var file = new System.IO.StreamWriter('log.txt');
file.WriteLine("Hello World");
file.Dispose();
三方库
比如shortid的
- 引擎
return new Engine(options =>
{
options.ExperimentalFeatures=ExperimentalFeature.All;
var asdemo = typeof(ShortId).GetTypeInfo().Assembly;
options.AllowClr([asdemo]);
});
- 代码使用
需要通过importNamespace 引用,我们也可以使用类似require 的模式 globalThis.require = importNamespace;
_engine.Modules.Add("@scope/platform-common", builder =>
{
builder.ExportObject("platform", platform);
builder.AddSource("globalThis.require = importNamespace;");
});
- 使用
let shortid = require("shortid");
let id = shortid.ShortId.Generate();
console.log("myid: "+id);
通过引入type 模式
此模式实际上就是,引入了新的类型,设置了一个全局变量
engine.SetValue("TheType", TypeReference.CreateTypeReference<TheType>(engine));
说明
以上是一个对于使用clr 类型的说明,当然js引入clr 的执行是会有安全风险的,注意防范