The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
guonaihong

golang “非主流”技巧 分享(1) --生成 c 可调用代码

  •  
  •   guonaihong ·
    guonaihong · Oct 5, 2019 · 3638 views
    This topic created in 2434 days ago, the information mentioned may be changed or developed.

    golang 得益与强大的生态,开发起来顺风顺水。c 语言作为老牌高性能语言,还是很多童鞋的最爱,但是开发效率是硬伤。假如要在 c 庞大的协议框架代码上改来该去,又或者要写个 c 网络通信的 sdk(提供 http 或者 websocket 协议)。有没有快速的方法搞定这些事情,这两个语言能不能摩擦出火花。还真的可以。。。请看下面的例子

    导出字符串函数给 c 用

    下面把 go 里面的 ReplaceAll 函数导出给 c 用。
    函数上面的 export ReplaceStrAll 是必须的,告诉编译器,你要什么名字的 c 函数

    • 包装 go 函数到 c 里面
    package main
    
    import (
        "strings"
    )
    
    import "C" 
    
    //export ReplaceStrAll
    func ReplaceStrAll(str *C.char, old *C.char, new *C.char) (rv *C.char) {
    
        s := C.GoString(str)
        oldStr := C.GoString(old)
        newStr := C.GoString(new)
    
        repRv := strings.Replace(s, oldStr, newStr, -1) 
        rv = C.CString(repRv)
        return
    }
    
    func main() {
    }
    
    
    • 编译命令(生成 c 静态库)
    env GOPATH=`pwd` go build -buildmode=c-archive -o replace.a replace.go
    
    • 使用
    #include <stdio.h>
    #include <stdlib.h>
    #include "replace.h"
    
    int main() {
    	char * p = ReplaceStrAll("aaa hello world bbb hello world ccc hello world ddd", "hello world", "");
    	printf("%s\n", p);
    	free(p);
    	return 0;
    }
    
    
    • 编译命令
    gcc -I .  use.c replace.a -Wall -lpthread
    

    未完待续

    由于要做饭,后面还有几个例子等有时间完善。

    github

    https://github.com/guonaihong/gout

    5 replies    2019-10-05 13:39:24 +08:00
    bumz
        1
    bumz  
       Oct 5, 2019 via iPhone
    好奇下,C 调用 Go 代码,那 Go 运行时咋办
    banxi1988
        2
    banxi1988  
       Oct 5, 2019
    这个编译出来的库体积大吗?
    reus
        3
    reus  
       Oct 5, 2019
    @bumz go 运行时会初始化。而且只能有一个初始化,所以你想链接两个 .a,是不行的,因为两套运行时会导致符号冲突。所以使用场景限制是比较大的。
    guonaihong
        5
    guonaihong  
    OP
       Oct 5, 2019
    @banxi1988 大,golang 语言特色。刚刚的代码编译的库大约 3.4MB
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5335 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 06:52 · PVG 14:52 · LAX 23:52 · JFK 02:52
    ♥ Do have faith in what you're doing.