go 的 cgo 怎么用啊?

2021-01-10 13:04:29 +08:00
 lysS

这段代码直接报错:

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))
}

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

637 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/743512

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX