How to use vectors (of C++ STL) with WebAssembly

余生长醉 提交于 2019-12-08 02:01:50

问题


#include <iostream>
#include<vector>
using namespace std;

vector<int> ver;

int pushData(int n)
{
    for(int i=0;i<n;i++)
    {
        ver.push_back(i);
    }
}

I want to call pushData function from JS and push some data to vector "ver" and use it later. please explain how to do that using WebAssembly.


回答1:


I tried to answer your question, by using this answer: https://stackoverflow.com/a/46748966/544721

to make solution :

#include<vector>
const int SIZE = 10;
std::vector<int> data(10);

void add(int value) { 
  for (int i=0; i<SIZE; i++) {
    data[i] = data[i] + value;
  }
}

int* getData() {
  return &(data[0]);
}

and js:

var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);

var offset = wasmInstance.exports.getData();

var linearMemory = new Uint32Array(wasmInstance.exports.memory.buffer, offset, 10);
for (var i = 0; i < linearMemory.length; i++) {
  linearMemory[i] = i;
}

wasmInstance.exports.add(10);

for (var i = 0; i < linearMemory.length; i++) {
  log(linearMemory[i]);
}

WasmFiddle: https://wasdk.github.io/WasmFiddle//?wuycy

But it looks like there is some linker error:

line 2: Uncaught LinkError: WebAssembly Instantiation: Import #9 module="env" function="__dso_handle" error: global import must be a number

Can anyone help to make this C++ code to run in WasmFiddle?




回答2:


i'm do something like you.In my opinion, using STL in WASM is very difficult.

My solution is to create a simulate vector.Wasm only supports int32, int64, float32 and float64 and wasm's adderess is differnt from other process.So it is not feasible to import the library directly. You can call the library function through a proxy or conversion.Or you can write it by yourself.

In this case, vector can't be imported directly.You can create a class named vector,and implement the push_back function.

class vector{
public:
    bool push_back(int i){
       // do something
    }
    int& at(uint index){
       // do something
    }
private:
    int* int_ptr;
}

More details here https://aransentin.github.io/cwasm/



来源:https://stackoverflow.com/questions/50220966/how-to-use-vectors-of-c-stl-with-webassembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!