How to pass pointer to slice to C function in go

前端 未结 1 1595
暗喜
暗喜 2020-12-19 13:45

Background: using cgo to call C functions from Golang.

I want to use a C function which has this signature: int f(int *count, char ***strs). It will mod

相关标签:
1条回答
  • 2020-12-19 13:53

    A Go slice is both allocated in Go, and a different data structure than a C array, so you can't pass it to a C function (cgo will also prevent you from doing this because a slice contains a Go pointer)

    You need to allocate the array in C in order to manipulate the array in C. Just like with C.CString, you will also need to track where to free the outer array, especially if the C function may possibly allocate a new array.

    cArray := C.malloc(C.size_t(c_count) * C.size_t(unsafe.Sizeof(uintptr(0))))
    
    // convert the C array to a Go Array so we can index it
    a := (*[1<<30 - 1]*C.char)(cArray)
    for index, value := range strs {
        a[index] = C.CString(value)
    }
    
    err := C.f(&c_count, (***C.char)(unsafe.Pointer(&cArray)))
    
    0 讨论(0)
提交回复
热议问题