After reading https://golang.org/cmd/cgo/#hdr-Passing_pointers and 
https://blog.golang.org/c-go-cgo,
I am trying to understand if there are valid ways to pass between Go and C 
complicated data structures
with (potentially) lots of pointers.

At the moment this is just a speculative question, but it could quickly 
become useful both for my Go interpreter gomacro
and for other similar tasks (I am thinking at least about 
https://github.com/gijit/gi) that need to pass arbitrary
data structures between compiled Go code and the interpreter itself (which 
may not be written in Go).

The question is: is it allowed to take the unsafe.Pointer returned by 
C.malloc() and convert it to a pointer to a Go struct type?

In practice: is the following code valid ?

Thanks,

Max

// 
-----------------------------------------------------------------------------------------

package main

/*
#include <string.h>
*/
import "C"

import (
    "fmt"
    "unsafe"
)

type List struct {
    Node int
    Next *List
}

func mallocList() *List {
    const n = unsafe.Sizeof(List{})
    p := C.malloc(C.ulong(n))
    C.memset(p, C.int(n), 0)
    return (*List)(p)
}

func main() {
    // if this code is valid, x can contain C pointers and can be passed 
freely to C code,
    // thus exchanging complicated data structured between Go and C

    x := mallocList()
    x.Next = mallocList()

    fmt.Printf("%#v\n", x)
    fmt.Printf("%#v\n", x.Next)
}

-- 
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.

Reply via email to