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 · 2 comments
Open

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

bcmills opened this issue Apr 4, 2017 · 2 comments
Milestone

Comments

@bcmills
Copy link
Member

@bcmills 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
Member Author

@bcmills bcmills commented Apr 4, 2017

Loading

@bradfitz bradfitz added this to the Go1.9Maybe milestone Apr 5, 2017
@bradfitz bradfitz removed this from the Go1.9Maybe milestone Jul 20, 2017
@bradfitz bradfitz added this to the Go1.10 milestone Jul 20, 2017
@bradfitz bradfitz added this to the Go1.10 milestone Jul 20, 2017
@bradfitz bradfitz removed this from the Go1.9Maybe milestone Jul 20, 2017
@rsc rsc removed this from the Go1.10 milestone Nov 22, 2017
@rsc rsc added this to the Go1.11 milestone Nov 22, 2017
@gopherbot gopherbot removed this from the Go1.11 milestone May 23, 2018
@gopherbot gopherbot added this to the Unplanned milestone May 23, 2018
@marxangels
Copy link

@marxangels marxangels commented May 23, 2020

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

this work for me

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
5 participants