dtqjbbr5283 2015-10-04 21:23
浏览 635
已采纳

Cgo:找不到使用带有const char *参数的回调的方法

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?

  • 写回答

1条回答 默认 最新

  • doukuilian8365 2015-10-05 02:22
    关注

    Since Go does not have const modifiers for pointers there is no way to translate this behaviour from inside Go code. cgo will always generate headers that do not have the const modifier. This is also the reason why your code does not build correctly: cgo creates myFunc only based on what it knows: buf should be char*, not const char*.

    The best way to handle this is to use wrapper on the C side that casts that parameter to const char*. In your case it is enough to change the definition of myFunc to void myFunc(char*, int). Passing the function to cb_func will work regardless since casting myFunc to (*cb_func)(const char*,int) only adds type information but does not change the memory layout.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 安装 opencv4nodejs 报错
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!