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 · 1 comment

Comments

Projects
None yet
4 participants
@bcmills
Member

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

This comment has been minimized.

Member

bcmills commented Apr 4, 2017

@bradfitz bradfitz added this to the Go1.9Maybe milestone Apr 5, 2017

@bradfitz bradfitz modified the milestones: Go1.9Maybe, Go1.10 Jul 20, 2017

@rsc rsc modified the milestones: Go1.10, Go1.11 Nov 22, 2017

@gopherbot gopherbot modified the milestones: Go1.11, Unplanned May 23, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment