CGO error : cannot use f ( type func(_Ctype_int, **_Ctype_char) _Ctype_int) as *[0]byte value in argument

552 views
Skip to first unread message

ulis lee

unread,
Nov 21, 2023, 10:28:20 PM11/21/23
to golang-nuts

Hi, all

It's been a month since I started Golang.
But I was in a difficult situation. I need your help.

C code

int reopen (const char *fn, time_t check_interval_sec, int (*callback_func) (int num_entry, char **entry), int retry);


Go code

func _Open(fileName string, intervalSec int, f func(C.int, **C.char) C.int) int {

   cFileName := C.CString(fileName)

   defer C.free(unsafe.Pointer(cFileName))


    ret := C.reopen(cFileName, C.long(intervalSec), f, 1)

    return int(ret)

}

error message 
cannot use f (variable of type func(_Ctype_int, **_Ctype_char) _Ctype_int) as *[0]byte value in argument to (_Cfunc_reopen)

Tzu-Yu Lee

unread,
Nov 22, 2023, 12:06:54 AM11/22/23
to golang-nuts
Hi,

You cannot pass f, which is a Go function, in a CGo call directly because of the pointer passing rules. You need to create some wrappers, and I have found this article (https://eli.thegreenplace.net/2019/passing-callbacks-and-pointers-to-cgo) very helpful.

That being said, I have a feeling that if you provide some more details about what you are trying to achieve, people here might be able to help you get a simpler solution in Go.

Tzu-Yu
ulis lee 在 2023年11月22日 星期三上午11:28:20 [UTC+8] 的信中寫道:

Kurtis Rader

unread,
Nov 22, 2023, 12:17:22 AM11/22/23
to ulis lee, golang-nuts
I think the error is trying to tell you the C reopen function takes a pointer to a function and you are passing it a Go func. Try googling "cgo pass function pointer". That should yield documents like https://eli.thegreenplace.net/2019/passing-callbacks-and-pointers-to-cgo/ which should point you in the right direction. I have to say, trying to do something like this after using Go for just one month is very ambitious. I think you are going to run into lots of problems due to your lack of experience with Go (not Golang).

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/644e20e4-0734-4fe7-be0e-0b4d101df1fdn%40googlegroups.com.


--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank
Reply all
Reply to author
Forward
0 new messages