douhuangjie4503 2019-03-01 06:01
浏览 181
已采纳

CGO库构建为JS WASM文件

I wanna write JS script using webassembly library builded from Golang. But I need to use C library and use it through CGO.

In short my code looks like this (just example of loading C libraries):

package main

/*
#include <stdlib.h>
*/
import "C"

func main() {
    println("Hello")
}

But when I wanna build it as in tutorial with command bellow I have error.

Command:

GOARCH=wasm GOOS=js go build -o lib.wasm test.go

Output:

can't load package: package main: build constraints exclude all Go files in [Project path]

So my question is more if it's even possible to build something like this.

Thank you.

  • 写回答

1条回答 默认 最新

  • drn34916 2019-03-01 06:35
    关注

    That won't fly: GOARCH=wasm GOOS=js basically makes the Go compiler to produce wasm bytecode from the Go source. To spell this in other words, the Go code gets compiled to WASM bytecode and the WASM API calls instead of CPU-specific machine code and system calls to a particular OS kernel.

    On the other hand, cgo is a way to link the compiled C code with the compiled Go code. To compile a program making use of cgo, the go toolchain calls out to a real C compiler (gcc most of the time), which compiles the C parts.

    Compiled C code and WASM bytecode exist in different universes and do not know about each other. In theory, a C compiler such as gcc could have a WASM backed—just like go has now—but IIRC this is neither the case nor the Go's WASM backend is taught to somehow handle such a case.

    All-in-all, the most typical case for using cgo is interfacing with an already existing library written in C (or exposing a C-compatible API), and most of such libraries usually make profound assumptions about the environment they run in—which typically is a POSIX-compatible OS (with a set of syscalls to handle file and socket I/O and so on).

    Hence if you are in a rare position of having the need to link with a "pure" C library—which performs pure data processing and does not communicate with an underlying OS in any way, it might be possible to look at a C-to-Go source-code translator.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部