当前位置:首页 > 文章列表 > Golang > Go问答 > Error in linking WebAssembly: function import had to be callable for "runtime.resetMemoryDataView" in module "go"

Error in linking WebAssembly: function import had to be callable for "runtime.resetMemoryDataView" in module "go"

来源:stackoverflow 2024-03-04 14:12:27 0浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《Error in linking WebAssembly: function import had to be callable for "runtime.resetMemoryDataView" in module "go"》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

当我构建 web 组装应用程序时,我遇到了一个神秘错误的问题:

linkerror: webassembly.instantiate(): import #1 module="go" function="runtime.resetmemorydataview" 错误:函数导入需要可调用

它是用这个命令编译的:

goos=js goarch=wasm go build -o main.wasm main.go server.go

这是index.html的正文,里面什么都没有


    
    

这是 main.go:

import (
    "fmt"
    "strconv"
    "syscall/js"
)

func key(this js.value, arg []js.value) interface{} {
    arg[0].call("stoppropagation")
    arg[0].call("preventdefault")
    return nil
}

func sum(this js.value, args []js.value) interface{} {
    var rv interface{}
    value1 := js.global().get("document").call("getelementbyid", args[0].string()).get("value").string()
    value2 := js.global().get("document").call("getelementbyid", args[1].string()).get("value").string()

    int1, _ := strconv.atoi(value1)
    int2, _ := strconv.atoi(value2)

    js.global().get("document").call("getelementbyid", "result").set("value", int1+int2)
    return rv
}

func register_callbacks() {
    js.global().set("key", js.funcof(key))
    js.global().set("sum", js.funcof(sum))
}

func init() {
    register_callbacks()
    fmt.printf("webassembly program started\n")
    select {}
}

然后我们就有了服务器:

package main

import (
    "flag"
    "fmt"
    "net/http"
)

var listen = flag.string("listen", ":8081", "listen address")
var dir = flag.string("dir", ".", "directory to serve")

func main() {
    flag.parse()
    fs := http.fileserver(http.dir("./assets/"))
    http.handle("/", fs)
    fmt.printf("web server running. listening on %q", *listen)
    err := http.listenandserve(*listen, http.fileserver(http.dir(*dir)))
    fmt.printf("%v\n", err)
}

这是 wasm_exec.js:

// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

(() => {
    if (typeof global !== "undefined") {
        // global already exists
    } else if (typeof window !== "undefined") {
        window.global = window;
    } else if (typeof self !== "undefined") {
        self.global = self;
    } else {
        throw new Error("cannot export Go (neither global, window nor self is defined)");
    }

    // Map web browser API and Node.js API to a single common API (preferring web standards over Node.js API).
    const isNodeJS = global.process && global.process.title === "node";
    if (isNodeJS) {
        global.require = require;
        global.fs = require("fs");

        const nodeCrypto = require("crypto");
        global.crypto = {
            getRandomValues(b) {
                nodeCrypto.randomFillSync(b);
            },
        };

        global.performance = {
            now() {
                const [sec, nsec] = process.hrtime();
                return sec * 1000 + nsec / 1000000;
            },
        };

        const util = require("util");
        global.TextEncoder = util.TextEncoder;
        global.TextDecoder = util.TextDecoder;
    } else {
        let outputBuf = "";
        global.fs = {
            constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
            writeSync(fd, buf) {
                outputBuf += decoder.decode(buf);
                const nl = outputBuf.lastIndexOf("\n");
                if (nl != -1) {
                    console.log(outputBuf.substr(0, nl));
                    outputBuf = outputBuf.substr(nl + 1);
                }
                return buf.length;
            },
            write(fd, buf, offset, length, position, callback) {
                if (offset !== 0 || length !== buf.length || position !== null) {
                    throw new Error("not implemented");
                }
                const n = this.writeSync(fd, buf);
                callback(null, n);
            },
            open(path, flags, mode, callback) {
                const err = new Error("not implemented");
                err.code = "ENOSYS";
                callback(err);
            },
            read(fd, buffer, offset, length, position, callback) {
                const err = new Error("not implemented");
                err.code = "ENOSYS";
                callback(err);
            },
            fsync(fd, callback) {
                callback(null);
            },
        };
    }

    const encoder = new TextEncoder("utf-8");
    const decoder = new TextDecoder("utf-8");

    global.Go = class {
        constructor() {
            this.argv = ["js"];
            this.env = {};
            this.exit = (code) => {
                if (code !== 0) {
                    console.warn("exit code:", code);
                }
            };
            this._exitPromise = new Promise((resolve) => {
                this._resolveExitPromise = resolve;
            });
            this._pendingEvent = null;
            this._scheduledTimeouts = new Map();
            this._nextCallbackTimeoutID = 1;

            const mem = () => {
                // The buffer may change when requesting more memory.
                return new DataView(this._inst.exports.mem.buffer);
            }

            const setInt64 = (addr, v) => {
                mem().setUint32(addr + 0, v, true);
                mem().setUint32(addr + 4, Math.floor(v / 4294967296), true);
            }

            const getInt64 = (addr) => {
                const low = mem().getUint32(addr + 0, true);
                const high = mem().getInt32(addr + 4, true);
                return low + high * 4294967296;
            }

            const loadValue = (addr) => {
                const f = mem().getFloat64(addr, true);
                if (f === 0) {
                    return undefined;
                }
                if (!isNaN(f)) {
                    return f;
                }

                const id = mem().getUint32(addr, true);
                return this._values[id];
            }

            const storeValue = (addr, v) => {
                const nanHead = 0x7FF80000;

                if (typeof v === "number") {
                    if (isNaN(v)) {
                        mem().setUint32(addr + 4, nanHead, true);
                        mem().setUint32(addr, 0, true);
                        return;
                    }
                    if (v === 0) {
                        mem().setUint32(addr + 4, nanHead, true);
                        mem().setUint32(addr, 1, true);
                        return;
                    }
                    mem().setFloat64(addr, v, true);
                    return;
                }

                switch (v) {
                    case undefined:
                        mem().setFloat64(addr, 0, true);
                        return;
                    case null:
                        mem().setUint32(addr + 4, nanHead, true);
                        mem().setUint32(addr, 2, true);
                        return;
                    case true:
                        mem().setUint32(addr + 4, nanHead, true);
                        mem().setUint32(addr, 3, true);
                        return;
                    case false:
                        mem().setUint32(addr + 4, nanHead, true);
                        mem().setUint32(addr, 4, true);
                        return;
                }

                let ref = this._refs.get(v);
                if (ref === undefined) {
                    ref = this._values.length;
                    this._values.push(v);
                    this._refs.set(v, ref);
                }
                let typeFlag = 0;
                switch (typeof v) {
                    case "string":
                        typeFlag = 1;
                        break;
                    case "symbol":
                        typeFlag = 2;
                        break;
                    case "function":
                        typeFlag = 3;
                        break;
                }
                mem().setUint32(addr + 4, nanHead | typeFlag, true);
                mem().setUint32(addr, ref, true);
            }

            const loadSlice = (addr) => {
                const array = getInt64(addr + 0);
                const len = getInt64(addr + 8);
                return new Uint8Array(this._inst.exports.mem.buffer, array, len);
            }

            const loadSliceOfValues = (addr) => {
                const array = getInt64(addr + 0);
                const len = getInt64(addr + 8);
                const a = new Array(len);
                for (let i = 0; i < len; i++) {
                    a[i] = loadValue(array + i * 8);
                }
                return a;
            }

            const loadString = (addr) => {
                const saddr = getInt64(addr + 0);
                const len = getInt64(addr + 8);
                return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
            }

            const timeOrigin = Date.now() - performance.now();
            this.importObject = {
                go: {
                    // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
                    // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
                    // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
                    // This changes the SP, thus we have to update the SP used by the imported function.

                    // func wasmExit(code int32)
                    "runtime.wasmExit": (sp) => {
                        const code = mem().getInt32(sp + 8, true);
                        this.exited = true;
                        delete this._inst;
                        delete this._values;
                        delete this._refs;
                        this.exit(code);
                    },

                    // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
                    "runtime.wasmWrite": (sp) => {
                        const fd = getInt64(sp + 8);
                        const p = getInt64(sp + 16);
                        const n = mem().getInt32(sp + 24, true);
                        fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
                    },

                    // func nanotime() int64
                    "runtime.nanotime": (sp) => {
                        setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
                    },

                    // func walltime() (sec int64, nsec int32)
                    "runtime.walltime": (sp) => {
                        const msec = (new Date).getTime();
                        setInt64(sp + 8, msec / 1000);
                        mem().setInt32(sp + 16, (msec % 1000) * 1000000, true);
                    },

                    // func scheduleTimeoutEvent(delay int64) int32
                    "runtime.scheduleTimeoutEvent": (sp) => {
                        const id = this._nextCallbackTimeoutID;
                        this._nextCallbackTimeoutID++;
                        this._scheduledTimeouts.set(id, setTimeout(
                            () => { this._resume(); },
                            getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
                        ));
                        mem().setInt32(sp + 16, id, true);
                    },

                    // func clearTimeoutEvent(id int32)
                    "runtime.clearTimeoutEvent": (sp) => {
                        const id = mem().getInt32(sp + 8, true);
                        clearTimeout(this._scheduledTimeouts.get(id));
                        this._scheduledTimeouts.delete(id);
                    },

                    // func getRandomData(r []byte)
                    "runtime.getRandomData": (sp) => {
                        crypto.getRandomValues(loadSlice(sp + 8));
                    },

                    // func stringVal(value string) ref
                    "syscall/js.stringVal": (sp) => {
                        storeValue(sp + 24, loadString(sp + 8));
                    },

                    // func valueGet(v ref, p string) ref
                    "syscall/js.valueGet": (sp) => {
                        const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
                        sp = this._inst.exports.getsp(); // see comment above
                        storeValue(sp + 32, result);
                    },

                    // func valueSet(v ref, p string, x ref)
                    "syscall/js.valueSet": (sp) => {
                        Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
                    },

                    // func valueIndex(v ref, i int) ref
                    "syscall/js.valueIndex": (sp) => {
                        storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
                    },

                    // valueSetIndex(v ref, i int, x ref)
                    "syscall/js.valueSetIndex": (sp) => {
                        Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
                    },

                    // func valueCall(v ref, m string, args []ref) (ref, bool)
                    "syscall/js.valueCall": (sp) => {
                        try {
                            const v = loadValue(sp + 8);
                            const m = Reflect.get(v, loadString(sp + 16));
                            const args = loadSliceOfValues(sp + 32);
                            const result = Reflect.apply(m, v, args);
                            sp = this._inst.exports.getsp(); // see comment above
                            storeValue(sp + 56, result);
                            mem().setUint8(sp + 64, 1);
                        } catch (err) {
                            storeValue(sp + 56, err);
                            mem().setUint8(sp + 64, 0);
                        }
                    },

                    // func valueInvoke(v ref, args []ref) (ref, bool)
                    "syscall/js.valueInvoke": (sp) => {
                        try {
                            const v = loadValue(sp + 8);
                            const args = loadSliceOfValues(sp + 16);
                            const result = Reflect.apply(v, undefined, args);
                            sp = this._inst.exports.getsp(); // see comment above
                            storeValue(sp + 40, result);
                            mem().setUint8(sp + 48, 1);
                        } catch (err) {
                            storeValue(sp + 40, err);
                            mem().setUint8(sp + 48, 0);
                        }
                    },

                    // func valueNew(v ref, args []ref) (ref, bool)
                    "syscall/js.valueNew": (sp) => {
                        try {
                            const v = loadValue(sp + 8);
                            const args = loadSliceOfValues(sp + 16);
                            const result = Reflect.construct(v, args);
                            sp = this._inst.exports.getsp(); // see comment above
                            storeValue(sp + 40, result);
                            mem().setUint8(sp + 48, 1);
                        } catch (err) {
                            storeValue(sp + 40, err);
                            mem().setUint8(sp + 48, 0);
                        }
                    },

                    // func valueLength(v ref) int
                    "syscall/js.valueLength": (sp) => {
                        setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
                    },

                    // valuePrepareString(v ref) (ref, int)
                    "syscall/js.valuePrepareString": (sp) => {
                        const str = encoder.encode(String(loadValue(sp + 8)));
                        storeValue(sp + 16, str);
                        setInt64(sp + 24, str.length);
                    },

                    // valueLoadString(v ref, b []byte)
                    "syscall/js.valueLoadString": (sp) => {
                        const str = loadValue(sp + 8);
                        loadSlice(sp + 16).set(str);
                    },

                    // func valueInstanceOf(v ref, t ref) bool
                    "syscall/js.valueInstanceOf": (sp) => {
                        mem().setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16));
                    },

                    "debug": (value) => {
                        console.log(value);
                    },
                }
            };
        }

        async run(instance) {
            this._inst = instance;
            this._values = [ // TODO: garbage collection
                NaN,
                0,
                null,
                true,
                false,
                global,
                this._inst.exports.mem,
                this,
            ];
            this._refs = new Map();
            this.exited = false;

            const mem = new DataView(this._inst.exports.mem.buffer)

            // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
            let offset = 4096;

            const strPtr = (str) => {
                let ptr = offset;
                new Uint8Array(mem.buffer, offset, str.length + 1).set(encoder.encode(str + "\0"));
                offset += str.length + (8 - (str.length % 8));
                return ptr;
            };

            const argc = this.argv.length;

            const argvPtrs = [];
            this.argv.forEach((arg) => {
                argvPtrs.push(strPtr(arg));
            });

            const keys = Object.keys(this.env).sort();
            argvPtrs.push(keys.length);
            keys.forEach((key) => {
                argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
            });

            const argv = offset;
            argvPtrs.forEach((ptr) => {
                mem.setUint32(offset, ptr, true);
                mem.setUint32(offset + 4, 0, true);
                offset += 8;
            });

            this._inst.exports.run(argc, argv);
            if (this.exited) {
                this._resolveExitPromise();
            }
            await this._exitPromise;
        }

        _resume() {
            if (this.exited) {
                throw new Error("Go program has already exited");
            }
            this._inst.exports.resume();
            if (this.exited) {
                this._resolveExitPromise();
            }
        }

        _makeFuncWrapper(id) {
            const go = this;
            return function () {
                const event = { id: id, this: this, args: arguments };
                go._pendingEvent = event;
                go._resume();
                return event.result;
            };
        }
    }

    if (isNodeJS) {
        if (process.argv.length < 3) {
            process.stderr.write("usage: go_js_wasm_exec [wasm binary] [arguments]\n");
            process.exit(1);
        }

        const go = new Go();
        go.argv = process.argv.slice(2);
        go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
        go.exit = process.exit;
        WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
            process.on("exit", (code) => { // Node.js exits if no event handler is pending
                if (code === 0 && !go.exited) {
                    // deadlock, make Go print error and stack traces
                    go._pendingEvent = { id: 0 };
                    go._resume();
                }
            });
            return go.run(result.instance);
        }).catch((err) => {
            throw err;
        });
    }
})();

解决方案


runtime.resetmemorydataview() 函数是 wasm_exec.js 支持脚本的一部分,该脚本将 webassembly 二进制文件与 javascript 环境桥接起来。此错误和类似错误通常意味着 wasm_exec.js 与 webassembly 二进制文件不兼容,因为用于编译二进制文件的 golang 版本与从中获取的 wasm_exec.js 不同(通常较新)。

运行或传送 golang webassembly 二进制文件时,请务必确保您使用的 wasm_exec.js 支持脚本来自与编译二进制文件相同版本的 golang。您可以从 $(go env goroot)/misc/wasm/wasm_exec.js 复制它以确保确定。

有关更多详细信息,请参阅官方 golang WebAssembly wiki

正如 blami 建议的一个简单的:

cp $(go env GOROOT)/misc/wasm/wasm_exec.js ./path/to/old/wasm_exec.js

为我工作。

终于介绍完啦!小伙伴们,这篇关于《Error in linking WebAssembly: function import had to be callable for "runtime.resetMemoryDataView" in module "go"》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
如何在PHP中执行JavaScript函数?如何在PHP中执行JavaScript函数?
上一篇
如何在PHP中执行JavaScript函数?
在PHP中如何执行JavaScript函数
下一篇
在PHP中如何执行JavaScript函数
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 美图AI抠图:行业领先的智能图像处理技术,3秒出图,精准无误
    美图AI抠图
    美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
    15次使用
  • SEO标题PetGPT:智能桌面宠物程序,结合AI对话的个性化陪伴工具
    PetGPT
    SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
    15次使用
  • 可图AI图片生成:快手可灵AI2.0引领图像创作新时代
    可图AI图片生成
    探索快手旗下可灵AI2.0发布的可图AI2.0图像生成大模型,体验从文本生成图像、图像编辑到风格转绘的全链路创作。了解其技术突破、功能创新及在广告、影视、非遗等领域的应用,领先于Midjourney、DALL-E等竞品。
    43次使用
  • MeowTalk喵说:AI猫咪语言翻译,增进人猫情感交流
    MeowTalk喵说
    MeowTalk喵说是一款由Akvelon公司开发的AI应用,通过分析猫咪的叫声,帮助主人理解猫咪的需求和情感。支持iOS和Android平台,提供个性化翻译、情感互动、趣味对话等功能,增进人猫之间的情感联系。
    43次使用
  • SEO标题Traini:全球首创宠物AI技术,提升宠物健康与行为解读
    Traini
    SEO摘要Traini是一家专注于宠物健康教育的创新科技公司,利用先进的人工智能技术,提供宠物行为解读、个性化训练计划、在线课程、医疗辅助和个性化服务推荐等多功能服务。通过PEBI系统,Traini能够精准识别宠物狗的12种情绪状态,推动宠物与人类的智能互动,提升宠物生活质量。
    38次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码