首页 > 解决方案 > 在 PHP 中将 C 编译为 Wasm

问题描述

我正在做一个项目,我需要将 C 编译为 Web 程序集。我正在使用 PHP,所以最好是可以使用它的东西。在我的项目中,我从一个字符串(比如说 $foo)中获取输入,然后我想将它编译为 Web Assembly,以便我可以在 Javascript 中显示它。如果我在外部编译 C 代码,我已经有显示部分了,但是有没有办法直接编译这个字符串?我显示 Wasm 的代码:

let x = 'main.wasm';

let instance = null;
let memoryStates = new WeakMap();

function syscall(instance, n, args) {
  switch (n) {
    default:
      // console.log("Syscall " + n + " NYI.");
      break;
    case /* brk */ 45: return 0;
    case /* writev */ 146:
      return instance.exports.writev_c(args[0], args[1], args[2]);
    case /* mmap2 */ 192:
      debugger;
      const memory = instance.exports.memory;
      let memoryState = memoryStates.get(instance);
      const requested = args[1];
      if (!memoryState) {
        memoryState = {
          object: memory,
          currentPosition: memory.buffer.byteLength,
        };
        memoryStates.set(instance, memoryState);
      }
      let cur = memoryState.currentPosition;
      if (cur + requested > memory.buffer.byteLength) {
        const need = Math.ceil((cur + requested - memory.buffer.byteLength) / 65536);
        memory.grow(need);
      }
      memoryState.currentPosition += requested;
      return cur;
  }
}

let s = "";
fetch(x).then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.instantiate(bytes, {
    env: {
      __syscall0: function __syscall0(n) { return syscall(instance, n, []); },
      __syscall1: function __syscall1(n, a) { return syscall(instance, n, [a]); },
      __syscall2: function __syscall2(n, a, b) { return syscall(instance, n, [a, b]); },
      __syscall3: function __syscall3(n, a, b, c) { return syscall(instance, n, [a, b, c]); },
      __syscall4: function __syscall4(n, a, b, c, d) { return syscall(instance, n, [a, b, c, d]); },
      __syscall5: function __syscall5(n, a, b, c, d, e) { return syscall(instance, n, [a, b, c, d, e]); },
      __syscall6: function __syscall6(n, a, b, c, d, e, f) { return syscall(instance, n, [a, b, c, d, e, f]); },
      putc_js: function (c) {
        c = String.fromCharCode(c);
        if (c == "\n") {
          document.write(s);
          s = "";
        } else {
          s += c;
        }
      }
    }
  })
).then(results => {
  instance = results.instance;
}).catch(console.error);

PHP代码:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = stripos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = stripos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
$string = 'blah blah {start c}#include <iostream>{end c}';
$foo = get_string_between($string, '{start c}', '{end c}');
//Something to compile $foo to Wasm

标签: javascriptphpccompilationwebassembly

解决方案


推荐阅读