Skip to content

unable to use unsafe.Pointer as pointer to C struct in Go 1.8 #19181

@ghost

Description

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

go version go1.8 darwin/amd64

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

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/brandonhsiao/gocode"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.8/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.8/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/_v/1ll1sr8d3ml0j1gxhbkfmg580000gp/T/go-build439503373=/tmp/go-build -gno-record-gcc-switches -fno-common"
CXX="clang++"
CGO_ENABLED="1"
PKG_CONFIG="pkg-config"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"

What did you do?

package main

/*
#include <stdio.h>

typedef struct {
  int foo;
} CStruct;

void test(CStruct* p) {
  printf("%d", p->foo);
}
*/
import "C"
import "unsafe"

type CStruct _Ctype_CStruct

func main() {
  var x CStruct
  x.foo = 42

  C.test(unsafe.Pointer(&x))
}
$ go build main.go && ./main

What did you expect to see?

A working compilation, and 42 printed to the screen. This worked in Go 1.7, and the Go docs state

- A Pointer can be converted to a pointer value of any type.

What did you see instead?

$ go build main.go 
# command-line-arguments
./main.go:23: cannot use unsafe.Pointer(&x) (type unsafe.Pointer) as type *C.struct___0 in argument to _Cfunc_test

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions