I'm use C library from Go using Cgo and all good except callbacks. Library have callback setter, which takes pointer to callback func. Callback func itself written in go and exported using Cgo syntax.
Problem: I can make and export function with char *
argument, but can't with const char *
.
Code to illustrate:
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
", 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);
}
Output from 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);
^
Without const
qualifiers code compiles and works as expected.
What can be used insted of *C.char
to get const string in C?