Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/cgo: type error when using pointers to C functions #19835

Open
bcmills opened this issue Apr 4, 2017 · 3 comments
Open

cmd/cgo: type error when using pointers to C functions #19835

bcmills opened this issue Apr 4, 2017 · 3 comments
Labels
compiler/runtime Issues related to the Go compiler and/or runtime.
Milestone

Comments

@bcmills
Copy link
Contributor

bcmills commented Apr 4, 2017

If I try to pass a C function pointer back to C from Go, I get a type error. It appears that cgo is mapping the function pointer type to *[0]byte (since there isn't a direct way to express C function-pointer types in the Go type system), but it isn't inserting the correct type conversions when referring to function-pointer values:

cgocallback/main.go:

package main

/*
#include <stdio.h>

static void invoke(void (*f)()) {
	f();
}

void print_hello() {
	printf("Hello, !");
}
*/
import "C"

func main() {
	C.invoke(C.print_hello)
}
bcmills:~$ go build cgocallback
# cgocallback
src/cgocallback/main.go:17: cannot use _Cgo_ptr(_Cfpvar_fp_print_hello) (type unsafe.Pointer) as type *[0]byte in argument to _Cfunc_invoke

The workaround is to define a typedef for the function pointer type an explicitly convert to the typedef, but it would be nice if that workaround were not necessary.

package main

/*

typedef void (*closure)();
*/
import "C"

func main() {
	C.invoke(C.closure(C.print_hello))
}
bcmills:~$ go version
go version devel +2bbfa6f746 Thu Mar 9 15:36:43 2017 -0500 linux/amd64
@bcmills
Copy link
Contributor Author

bcmills commented Apr 4, 2017

(CC: @ianlancetaylor @thanm)

@marxangels
Copy link

marxangels commented May 23, 2020

func main() {
	C.invoke((*[0]byte)(C.print_hello))
}

this work for me

@gopherbot gopherbot added the compiler/runtime Issues related to the Go compiler and/or runtime. label Jul 13, 2022
@16892434
Copy link

func main() {
	C.invoke((*[0]byte)(C.print_hello))
}

this work for me

solved my question ! TKS !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
compiler/runtime Issues related to the Go compiler and/or runtime.
Projects
None yet
Development

No branches or pull requests

6 participants