我试图从 Swift 调用这个 C 函数并出现编译错误:// headerCURLcode curl_easy_setopt_callback(CURL *curl, CURLoption option, size_t (*param)(char*, size_t, size_t, vo...
我尝试从 Swift 调用此 C 函数并收到编译错误:
// header
CURLcode curl_easy_setopt_callback(CURL *curl, CURLoption option, size_t (*param)(char*, size_t, size_t, void*));
// c file
CURLcode curl_easy_setopt_callback(CURL *curl, CURLoption option, size_t (*param)(char*, size_t, size_t, void*)) {
return curl_easy_setopt(curl, option, param);
}
错误信息:
Type of expression is ambiguous without a type annotation
使用此代码:
typealias Callback = @convention(c) (
UnsafeMutableRawPointer?,
Int32,
Int32,
UnsafeMutableRawPointer?
) -> Int32
func testConnection() {
let curlHandle = curl_easy_init()
// https://support.google.com/accounts/answer/185833?hl=en
curl_easy_setopt_string(curlHandle, CURLOPT_USERNAME, "***@gmail.com")
curl_easy_setopt_string(curlHandle, CURLOPT_PASSWORD, "***")
curl_easy_setopt_string(curlHandle, CURLOPT_URL,
"imaps://imap.gmail.com:993//%5BGmail%5DSent%20Sent%20Mail");
let callback: Callback = { ptr, size, nmemb, userdata in
return 0
}
// Error on the next line: Type of expression is ambiguous without a type annotation
curl_easy_setopt_callback(curlHandle, CURLOPT_WRITEFUNCTION, callback);
print("curl_easy_perform")
let res = curl_easy_perform(curlHandle);
if(res != CURLE_OK) {
print("curl_easy_perform failed\(res)")
} else {
print("success!")
}
curl_easy_cleanup(curlHandle);
}
不确定我做错了什么。
我包装了 libcurl 的 curl_easy_setopt,因为 Swift 不喜欢可变参数函数。如果有办法摆脱这个包装器 - 我很乐意这么做。
我使用的是 Xcode 15.4,目标是 iOS 17.5。静态 libcurl 的版本是 8.10.1