On Tue, Apr 11, 2017 at 10:29 AM, Axel Wagner <axel.wagner...@googlemail.com> wrote: > > This begs the question how syscalls are handled. I assume they don't use > cgo, but often they require to pass a pointer to some memory which is > documented as a C-struct. Is there any guidance on that (or any problems > that might arise there)?
ObPedant: it *raises* the question, it doesn't *beg* the question. The syscall package (and the golang.org/x/sys/unix package) defines Go versions of a number of C structs used by system calls. Those Go versions are generated by cgo (run in a special mode, and with the generated files committed to the repository) and are accurate Go representations of the C structs. Ian > On Tue, Apr 11, 2017 at 6:41 PM, Ian Lance Taylor <i...@golang.org> wrote: >> >> On Tue, Apr 11, 2017 at 2:25 AM, hui zhang <fastfad...@gmail.com> wrote: >> > >> > If I define the same 2 struct in c and go >> > can they be passed directly with unsafe.Pointer >> >> The struct layout rules are under-defined in Go. The current rules >> are straightforward, and it is the case that most structs with the >> same sequence of field types will look the same in C and Go. Of >> course you must remember that `int` in Go is often not the same size >> as `int` in C. Also the alignment rules are not always the same, so >> don't permit any alignment padding. And this may change in future Go >> releases. >> >> > and how to export go struct from go to c ? >> >> You can't, not easily. But it's easy to use cgo to export a C struct >> from C to Go, and doing that avoids all the concerns about types and >> alignments, so you should do that if at all possible. >> >> >> > /* >> > #include <stdio.h> >> > >> > typedef struct { >> > int a; >> > int b; >> > } Foo; >> > >> > void pass_struct(Foo *in) { printf("%d : %d\n", in->a, in->b); } >> > >> > */ >> > >> > import "C" >> > >> > import ( >> > "fmt" >> > "unsafe" >> > ) >> > >> > type Foo struct{ a, b int32 } >> > >> > C.pass_struct((*C.Foo)(unsafe.Pointer(&foo))) >> >> For example, how about `type Foo C.Foo`? >> >> 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. >> For more options, visit https://groups.google.com/d/optout. > > -- 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. For more options, visit https://groups.google.com/d/optout.