douhuangjie4503 2019-03-01 14:01
浏览 180
已采纳

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 14: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.

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

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题