go: cmd/cgo: compiler accepts invalid declaration of methods on aliases to C types

This program successfully runs with Go 1.21:

$ cat cgo_methods.go
package main

/*
typedef int foo;
*/
import "C"

type foo = C.foo

func (foo) method() int { return 123 }

func main() {
	var x foo
	println(x.method()) // "123"
}
$ go run cgo_methods.go
123

I believe this program is invalid for the same reason as the program in https://github.com/golang/go/issues/57926. Note that in contrast to that issue, this program uses an alias to define a method on a C type.

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Comments: 15 (9 by maintainers)

Commits related to this issue

Most upvoted comments

@adonovan indeed, I submitted a PR to that repo with fix.

@alandonovan pointed out this hole in the current cgo detection of methods on C types, and I said it didn’t seem worth worrying about, because who would put a method on a type alias? Interesting to see that people actually do this.

If anybody sees a simple way to fix this, by all means go for it.

I think this condition is simple to fix this.

isCgoGeneratedFile(T.obj.Pos()) && strings.HasPrefix(T.obj.Name(), "_Ctype_") 

fix cl

@alandonovan pointed out this hole in the current cgo detection of methods on C types, and I said it didn’t seem worth worrying about, because who would put a method on a type alias? Interesting to see that people actually do this.

If anybody sees a simple way to fix this, by all means go for it.