【问题标题】:CGo: how to pass a 2 dimensional slice to C functionCGo:如何将二维切片传递给 C 函数
【发布时间】:2015-12-09 22:51:47
【问题描述】:

我的代码是:

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

当我使用go run test.go 运行时,它失败并说:

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

我的问题是如何将二维切片传递给 C 函数,如上面的 fill_2d_array

谢谢。

【问题讨论】:

    标签: go cgo


    【解决方案1】:

    解决者:
    C.fill_2d_array((*[16]C.char)(unsafe.Pointer(&amp;dirs)))

    【讨论】:

    • 这段代码刚刚通过编译。运行的时候就崩溃了。 :(
    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    相关资源
    最近更新 更多