lysS
V2EX  ›  问与答

go 的 cgo 怎么用啊?

  •  
  •   lysS · Jan 10, 2021 · 1134 views
    This topic created in 2019 days ago, the information mentioned may be changed or developed.

    这段代码直接报错:

    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 的类型,就有最开始那个问题; 给我整蒙了。。。。

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1055 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 22:51 · PVG 06:51 · LAX 15:51 · JFK 18:51
    ♥ Do have faith in what you're doing.