On Sun, Aug 06, 2017 at 07:08:03PM -0700, jianzhang...@gmail.com wrote:

> Thanks your reply, I also used this way, but it still not work. code as the 
> following.
> 
> gonameunits := []string{"gpu0", "gpu1", "gpu2", "gpu3"}
>    nameunits := make([]*C.char, len(gonameunits))
>    for i, _ := range gonameunits {
>        nameunits[i] = C.CString(gonameunits[i])
>        defer C.free(unsafe.Pointer(nameunits[i]))
>    }
>    fmt.Println("nameunits:", nameunits)

This looks correct...

>     golevelmatrix := [][]int{{1}, {3, 3}, {3, 3, 2}}
>    levelmatrix := make([][]C.int, len(golevelmatrix))
>    for i, _ := range golevelmatrix {
>        levelmatrix[i] = make([]C.int, len(golevelmatrix[i]))
>        for j, _ := range golevelmatrix[i] {
>            levelmatrix[i][j] = C.int(golevelmatrix[i][j])
>        }
>    }

...but this is not: remember that in Go, the type []T denotes *a slice* of
elements of type T.  A slice is a dynamic construct which is a view into
underlying array, and as such it itself consists of a pointer into that
array's contents, the current length of the slice and the capacity of
it.

>    fmt.Println("levelmatrix:", levelmatrix)
> 
>     C.test_settopologyresource(mod, C.CString("node1"), C.int(2), (**C.char
> )(unsafe.Pointer(&nameunits[0])), (**C.int)(unsafe.Pointer(&levelmatrix[0][0
> ])))

That thing about slices means that passing a pointer to a single slice
element to C is OK; passing a pointer to an Nth element of a slice to C
and expecting it to access it and the elements following it up to the
slice's length is also OK but interpreting a slice of slices (which
[][]*C.int really is) is wrong: it's not represented by a contiguous
array: it's a slice of N independent slices -- each backed by its
independent array.

So what you really want is something like:

1. Know the dimensions of your matrix (let's denote them by N and M).
2. Allocate a slice of the length N*M.
3. Fill it up with the values from your source slice of slices.
4. Pass the pointer to the array to C.

Like this (untested, may not even compile):

  n := len(golevelmatrix)
  m := 0
  for _, row := range golevelmatrix {
    if len(row) > m {
          m = len(row)
        }
  }
  
  a := make([]int, n*m)
  i := 0
  for _, row := range golevelmatrix {
        for j, v := range row {
                a[i*n+j] = v
        }
        i++
  }

  C.my_func(&a[0])

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