【发布时间】:2020-07-20 17:17:19
【问题描述】:
我正在使用来自 Go 的 C 库,使用 Cgo 并且除了回调之外一切都很好。库有回调设置器,它接受指向回调函数的指针。回调函数本身用 go 编写并使用 Cgo 语法导出。
问题:我可以使用char * 参数创建和导出函数,但不能使用const char *。
说明代码:
test.go:
package main
/*
typedef void (*cb_func)(const char *, int);
void callback(cb_func);
void myFunc(const char *, int);
*/
import "C"
import (
"fmt"
"unsafe"
)
//export myFunc
func myFunc(buf *C.char, ln C.int) {
fmt.Printf("Got: %s\n", C.GoStringN(buf, ln))
}
func main() {
C.callback((C.cb_func)(unsafe.Pointer(C.myFunc)))
}
test.c:
typedef void (*cb_func)(const char *, int);
void callback(cb_func cb) {
cb("test", 4);
}
来自go build的输出:
In file included from $WORK/test/_obj/_cgo_export.c:2:0:
./test.go:54:13: error: conflicting types for 'myFunc'
./test.go:7:6: note: previous declaration of 'myFunc' was here
void myFunc(const char *, int);
^
/tmp/go-build994908053/test/_obj/_cgo_export.c:9:6: error: conflicting types for 'myFunc'
void myFunc(char* p0, int p1)
^
In file included from $WORK/test/_obj/_cgo_export.c:2:0:
./test.go:7:6: note: previous declaration of 'myFunc' was here
void myFunc(const char *, int);
^
没有const 限定符的代码可以按预期编译和工作。
*C.char 的 insted 可以用来在 C 中获取 const 字符串吗?
【问题讨论】: