On Thu, Jul 22, 2021 at 2:53 PM Ami Ladani <amiladan...@gmail.com> wrote:
>
> I am trying to access members of a C struct from go. Compiler is showing 
> structure's members are undefined. I have attached my code and the error 
> message below.
>
> Please have a look and help if you can.
>
> $CGO_ENABLED=1 go run main.go cfuncs.go
> # command-line-arguments
> ./main.go:18:44: baz_ptr.b undefined (type *GoBaz has no field or method b)
> ./main.go:19:44: baz_ptr.f undefined (type *GoBaz has no field or method f)
>
> //c_header.h
> typedef void (*cb)(void* qux, int status, void *command_data, void *cb_data);
> typedef struct{
>   int a;
>   int b;
> } Foo;
>
> typedef struct{
>   char* ch;
>   cb callback;
> } Bar;
>
> typedef struct{
>   Foo* f;
>   Bar* b;
> } Baz;
> //--------------------------------
>
> //cfuncs.go
> package main
> /*
> #include<c_header.h>
> #include <stdlib.h>
>
> Baz* allocateBaz(){
>      Baz* baz = malloc(sizeof(Baz));
>      Bar* bar = malloc(sizeof(Bar));
>      Foo* foo = malloc(sizeof(Foo));
>      baz->f = foo;
>      baz->b = bar;
>      return baz;
> }
> */
> import "C"
> //-------------------------------------------------
>
> //main.go
> package main/*
> #include<c_header.h>
> extern Baz* allocateBaz();
> */
> import "C"
> import "unsafe"
> type GoBaz C.struct_Baz
> type GoBar C.struct_Bar
> type GoFoo C.struct_Foo
> func main() {
>   baz_ptr := (*GoBaz)(unsafe.Pointer(C.allocateBaz()))
>   bar_ptr := (*GoBar)(unsafe.Pointer(baz_ptr.b))
>   foo_ptr := (*GoFoo)(unsafe.Pointer(foo_ptr.f))
> }
> //--------------------------------


Interesting.  I think that has to do with the fact that you are using
two different Go files that both #include <c_header.h>.  <c_header.h>
uses typedef to define anonymous structs.  The fact that the header is
being included twice in the same package seems to be causing cgo to
generate two different Go structs, one for each .go file.  And then it
can't figure out the definition of the Go struct, so you get this
error.

This is probably a bug in cgo, so feel free to file an issue at
https://golang.org/issue.

You can probably make progress by combining the .go files so that you
only have a single import "C" with a #include <c_header.h>.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcWnYK3YVnLD%3D%2BEjA8XPJEYPvp0g6nej4xWeqY0xFjrgog%40mail.gmail.com.

Reply via email to