V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lysS
V2EX  ›  问与答

go 的 cgo 怎么用啊?

  •  
  •   lysS · 2021-01-10 13:04:29 +08:00 · 628 次点击
    这是一个创建于 1196 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这段代码直接报错:

    package main
    
    // #include <stdio.h>
    // #include <stdlib.h>
    /*
    void print(char *str) {
        printf("%s\n", str);
    }
    */
    import "C"
    
    import "unsafe"
    
    func main() {
    	s := "Hello Cgo"
    	cs := C.CString(s)
    	C.print(cs)
    	C.free(unsafe.Pointer(cs))
    }
    
    

    image.png

    说一下我的需求:golang 编译的 dll 动态库输出字符串
    如果是这段代码:

    import "C"
    
    func main() {
    	Hello_world()
    }
    
    //export Hello_world
    func Hello_world() string {
    	return "hello dart!!"
    }
    

    编译的 dll,使用 py 调用的结果是一串数字830403984

    from ctypes import CDLL, c_char_p
    
    dll = CDLL("./hello_world.dll")
    r = dll.Hello_world()
    print(r)
    

    查了一下,需要把 go 的 string 转换为对应的 C 的类型,就有最开始那个问题; 给我整蒙了。。。。

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2686 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 150ms · UTC 05:14 · PVG 13:14 · LAX 22:14 · JFK 01:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.