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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题