javascript - 在 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
解决方案
推荐阅读
- ios - 为什么 AdditionalSafeAreaInsets 会传播到子 VC?
- javascript - ASP.Net MVC:我如何通过@Url.Action() 将 js 数组传递给 mvc 动作
- java-8 - JDK8函数式编程一个函数可以抛出异常吗?
- jenkins - jenkins 在使用“sudo su”时通过 ssh 执行 shell 挂起
- wix - WiX 快捷方式未检测到应用程序目录中的文件
- windows - 用“逗号”替换动态字符串 - Windows 批处理文件
- excel - Excel VBA - 运行驻留在工作簿 A 中的宏以影响工作簿 B。B 的名称是通配符
- laravel - Laravel Notification markasread 不会更新通知表
- synology - ipkg 更新分段错误
- ios - 如何获取要删除的 Core Data 持久存储的 URL?