douke1891 2011-08-04 14:04
浏览 59
已采纳

如何从Go语言调用此C函数(使用Cgo工具)

Here is this C function declaration

CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);

how do I call this function from Go?

type Easy struct {
    curl unsafe.Pointer
    code C.CURLcode
}

func (e *Easy)SetOption(option C.CURLoption, ...) {
    e.code = C.curl_easy_setopt(e.curl, option, ????))
}
  • 写回答

1条回答 默认 最新

  • donglu8779 2011-08-04 15:17
    关注

    You can't call it directly. CGO does not play well with vararg functions on the C side. Ideally, you could create a C wrapper which accepts a list of options you want to pass. The C function should then expand that list into the variable arguments required by curl_easy_set_opt(). But I am not sure if that is possible or how to go about doing it.

    The signature for your Go function is also incorrect:

    type Option C.CURLoption
    
    func (e *Easy) SetOption(options ...Option) {
        // 'options' is now accessible as a slice: []Option
        // Turn this slice into a list of C.CURLoption pointers and pass it to
        // your C wrapper.
    
        if len(options) == 0 {
            return // No use continuing.
        }
    
        // Here is one way to convert the option slice to a list
        // that C can work with.
        size := int(unsafe.Sizeof(options[0]))
        list := C.malloc(C.size_t(size * len(options)))
        defer C.free(unsafe.Pointer(list)) // Free this after use!
    
        for i := range options {
            ptr := unsafe.Pointer( uintptr(list) + uintptr(size * i) )
            *(*C.CURLoption)(ptr) = C.CURLoption(options[i])
        }
    
        C.my_setopt_wrapper(e.curl, list, C.int(len(options)))
    }
    

    Note that the type of the option parameter has been changed to a go version of it. When someone uses your package, they have no access to the C.xxx types. So you should not use those in your public api. They are only meant for internal use in your package.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了