CGO:找不到使用带有const char *参数的回调的方法 [英] Cgo: can't find way to use callbacks with const char* argument

查看:303
本文介绍了CGO:找不到使用带有const char *参数的回调的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Cgo使用Go语言编写的C库,除了回调函数外,其他所有方法都很好。库具有回调设置程序,该程序使用指向回调函数的指针。用go编写的回调函数本身,并使用Cgo语法导出。

问题:我可以使用 char * 参数创建和导出函数,但不能使用 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 *.

说明代码:

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 插入的内容来获取const字符串C?

What can be used insted of *C.char to get const string in C?

推荐答案

因为Go没有用于指针的 const 修饰符无法从Go代码内部转换此行为。 cgo将始终生成不具有 const 修饰符的标头。这也是您的代码无法正确构建的原因: cgo 仅基于其所知道的内容来创建 myFunc 。 code> buf 应该是 char * ,而不是 const char *

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*.

处理此问题的最佳方法是在C侧使用包装器,该包装器将该参数转换为 const char * 。在您的情况下,只需将 myFunc 的定义更改为 void myFunc(char *,int)。将函数传递给 cb_func 将有效,无论将 myFunc 强制转换为(* cb_func)(const char *,int)仅添加类型信息,但不更改内存布局。

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.

这篇关于CGO:找不到使用带有const char *参数的回调的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆