golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.89k stars 17.52k forks source link

GO can't call C function #35371

Closed oathupdate closed 4 years ago

oathupdate commented 4 years ago

What version of Go are you using (go version)?

$ go version
go version go1.13.4 darwin/amd64

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
mac os10.13.6

What did you do?

package main

import(
    "fmt"
)
/*
struct Test {
    int a;
    int b;
    int (*plus)(int, int);
};

static int plus(int a, int b)
{
    return a + b;
}

#cgo LDFLAGS: -ldl
*/
import "C"

func GoPlus(ctx C.struct_Test) {
    fmt.Println(ctx.a)
    fmt.Println(ctx.plus(C.int(1), C.int(2)))
}

func main() {
}
go build -o plus.so -buildmode=c-shared plus.go
./plus.go:24:25: cannot call non-function ctx.plus (type *[0]byte)

What did you expect to see?

build success

What did you see instead?

./plus.go:24:25: cannot call non-function ctx.plus (type *[0]byte)

ianlancetaylor commented 4 years ago

This is an unfortunate limitation, but it is very difficult to fix, and it is documented. From https://golang.org/cmd/cgo, q.v.:

Calling C function pointers is currently not supported, however you can declare Go variables which hold C function pointers and pass them back and forth between Go and C. C code may call function pointers received from Go.