简体   繁体   English

使用js-interop将类型化数组缓冲区传递给dart中的javascript

[英]Passing typed array buffer to javascript from dart with js-interop

Trying to call a javascript method that required a typed array. 试图调用需要类型化数组的javascript方法。

var arrayData = js.array(new Uint8Array.fromList(data.charCodes));

Using js.array does not proxy it the way I was expecting, how could I pass the typed array as a typed array to a javascript method in dart? 使用js.array并不像我期望的那样代理它,我如何将类型化数组作为类型数组传递给dart中的javascript方法?

You can instantiate ArrayBuffer and Uint8Array javascript objects directly from Dart. 您可以直接从Dart实例化ArrayBufferUint8Array javascript对象。

If you need only a Uint8Array javascript object : 如果您只需要一个Uint8Array javascript对象:

js.scoped(() {
  final charCodes = "test".charCodes;
  final bufView = new js.Proxy(js.context.Uint8Array, js.array(charCodes));

  // do something with bufView
});

If you need an ArrayBuffer javascript object: 如果你需要一个ArrayBuffer javascript对象:

js.scoped(() {
  final charCodes = "test".charCodes;
  final buf = new js.Proxy(js.context.ArrayBuffer, charCodes.length);
  final bufView = new js.Proxy(js.context.Uint8Array, buf)
    ..set(js.array(charCodes));

  // do something with buf
});

Basically, each time you need to use the new javascript operator, you have to use new js.Proxy(construtor,...) . 基本上,每次你需要使用new javascript运算符时,你必须使用new js.Proxy(construtor,...)

WARNING : Until a new version has landed containing the pull-request #34 of js-interop , you have to use the following dependency to run the above code snippet. 警告 :在新版本下载包含js-interop的拉取请求#34之前 ,您必须使用以下依赖项来运行上面的代码片段。

dependencies:
  js:
    git: git://github.com/dart-lang/js-interop.git

A solution found was to create a utils.js and include the constructors for objects not loaded in the js.context. 找到的解决方案是创建一个utils.js并包含未在js.context中加载的对象的构造函数。

utils.js: utils.js:

var xArrayBuffer=function(length) {
    return new ArrayBuffer(length); 
};

var xUint8Array=function(buf) {
    return new Uint8Array(buf);
};

Include the utils.js in your index.html index.html中包含utils.js

  <body>
    <script src="utils.js"></script>
    <script src="dart.js"></script>
    <script src="example.dart.js"></script>
  </body>

Then call from a js.scoped closure. 然后从js.scoped闭包调用。 example.dart example.dart

  js.scoped(() {
    var jscore = js.context.jscore;        
    var buf = js.context.xArrayBuffer(data.charCodes.length);
    var bufView = js.context.xUint8Array(buf);

    for (var i = 0; i < data.charCodes.length; i++) {
      bufView[i] = data.charCodeAt(i);
    }

    jscore.writeArrayBuffer(buf);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM