简体   繁体   中英

CGo: how to pass a 2 dimensional slice to C function

My code is:

package main

/*                                                                                                                                                                                                                
#include <stdio.h>                                                                                                                                                                                                
#include <string.h>                                                                                                                                                                                               

void fill_2d_array(char (*s)[16]) {                                                                                                                                                                               
    strcpy(s[0], "hello");                                                                                                                                                                                        
    strcpy(s[1],"cgo");                                                                                                                                                                                           
}                                                                                                                                                                                                                 
*/
import "C"
import "fmt"
import "unsafe"

func main() {
        dirs := make([][]byte, 4)
        for i := 0; i < 4; i++ {
            dirs[i] = make([]byte, 16)
        }
        C.fill_2d_array(((*C.char)[16])(unsafe.Pointer(&dirs)))

        fmt.Println(dirs)
}

When I run with go run test.go , it failed and said:

./test.go:21: type *C.char is not an expression

My Question is how to pass a 2 dimensional slice to a C function like fill_2d_array above?

Thanks.

解决方案:
C.fill_2d_array((*[16]C.char)(unsafe.Pointer(&dirs)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM