如何在JS中使用C编译的WASM函数?指针逻辑未按预期工作

问题描述

我使用EMCC编译具有指针的c程序,并使用WebAssembly将其导入Angular 8中。 c函数似乎在js中可用,但是指针概念无法按预期工作。我完全感到困惑,因为javascript不使用指针概念。因此,我必须在那里做些什么。

下面是我的c程序,我将斐波那契数存储在作为指针的数组中。还更改了字符值,对其进行了修改

#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
int fibonacci_pointer(int *res,int n,char *ch) {
  res[0] = 0;
  if(n == 0) { return n; }
  res[1] = 1;
  if(n == 1) { return n; }
  for(int i = 2; i <= n; i++) {
    res[i] = res[i-1] + res[i-2];
  }
  ch = "Bye";
  return n;
}

我使用以下emcc命令编译了文件

emcc \
    fibonacci.c \
    -Os \
    -o fibonacci.wasm \
    --no-entry

我通过本地节点服务器提供了此WASM文件。最后在app.component.ts中的Angular 8应用程序中。我添加了以下代码

import { AfterViewInit,Component,OnInit } from '@angular/core';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit,AfterViewInit {
  title = 'FrontEnd';

  constructor() {}

  ngOnInit() {
    WebAssembly.instantiateStreaming(window.fetch('http://localhost:3000/fibonacci.wasm'),{
        imports: {
          imported_func: function(arg) {
            console.log(arg);
          },wasi_unstable: () => {}
        }
      })
      .then(async (obj) => {
        // Declare variable
        // tslint:disable-next-line: prefer-const
        let array = []; let n = 8; let str = 'Hi';

        // Print to validate of function present
        console.log(obj.instance.exports);

        // Call the function
        const fun: any = obj.instance.exports;
        console.log(fun.fibonacci_pointer(array,n,str));

        // Print to check if values modified
        console.log('Array: ',array,',N: ',str: ',str);
        // Expected: Array: [0,1,....],n: 8,str: Bye
        // Got: Array: [],str: Hi

      })
      .catch(err => {
          console.log('Unable to get WASM files. Please try again later: ',err);
          alert('Unable to get WASM files. Please try again later !');
          /* window.history.back(); */
      });
  }

}

下面是我的控制台输出图像。

enter image description here

如您所见,由于c函数可以正确返回n值,因此它可以使用并且可以正常工作。但是指针逻辑不起作用,因为数组仍然为空。

我错了吗?我在文档中搜索了很多内容。他们说支持指针。但这种方式行不通。我知道javascript没有指针。希望您对此有任何想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)