golang/go

cmd/cgo: emit forward-declarations for cgo-exported Go functions

Open

#19,837 opened on Apr 4, 2017

View on GitHub
 (6 comments) (6 reactions) (0 assignees)Go (19,008 forks)batch import
NeedsFixhelp wanted

Repository metrics

Stars
 (133,883 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

I'm trying to pass a Go function as a C function pointer.

I expect to be able to do that by exporting the Go function to C, then passing the C name of the Go function:

package main

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

typedef void (*closure)();  // https://golang.org/issue/19835
*/
import "C"

import "fmt"

//export go_print_hello
func go_print_hello() {
	fmt.Println("Hello, !")
}

func main() {
	C.invoke(C.closure(C.go_print_hello))
}

Unfortunately, that results in a cgo error:

bcmills:~$ go build cgocallback
# cgocallback
could not determine kind of name for C.go_print_hello

As a workaround, I can add an explicit forward-declaration of the Go function to the C preamble:

/*
…
void go_print_hello();
*/
import "C"

Given that cgo (presumably) already knows the C declarations for the functions it is exporting, I would prefer that it emit those forward-declarations itself. Since all C types should be defined by the end of the user-defined preamble, it seems like cgo could emit the forward declarations immediately following the preamble.

(If user code needs to refer to the Go functions within the preamble itself, requiring an explicit forward-declaration seems reasonable.)

bcmills:~$ go version
go version devel +2bbfa6f746 Thu Mar 9 15:36:43 2017 -0500 linux/amd64

Contributor guide