libCurl.继续进行时取消请求 [英] libCurl. Cancel request while proceed
问题描述
已更新:问题不在libcurl中.如果从回调非零值返回,则取消请求的正确方法.我使用了curl_progress_callback函数,一切正常.
UPDATED: Problem was not in libcurl. The right way to cancel request if to return from callback non-zero value. I used curl_progress_callback function, and everything works fine.
推荐答案
您需要了解的是CURL是C库.通常,您不能将指针传递给C ++对象或函数,因为C对C ++的类和调用约定一无所知.
What you need to understand is that CURL is a C library. In general, you cannot pass pointers to C++ objects or functions because C does not know anything about C++'s classes and calling convention.
例如,此行不正确:
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
CURL setopt CURLOPT_ERRORBUFFER
期望第三个参数是一个指向C样式字符串(C样式char
数组)的指针,该字符串具有用于CURL_ERROR_SIZE
字符的空间.而是将指针传递给std::string
对象.由于用C编写的CURL不知道std::string
是什么,因此它会简单地用错误数据覆盖具有sizeof (std::string)
字节的字节表示形式,因为它认为指针是C风格的char
数组.
CURL setopt CURLOPT_ERRORBUFFER
expects that the third parameter is a pointer to a C-style string (C-style char
array) having space for CURL_ERROR_SIZE
chars. You are instead passing a pointer to a std::string
object. As CURL, being written in C, does not know what a std::string
is, it simply overwrites the byte representation having sizeof (std::string)
bytes with the error data because it thinks that the pointer is to a C-style char
array.
改为使用此:
char errorBuffer[CURL_ERROR_SIZE + 1]; errorBuffer[CURL_ERROR_SIZE] = '\0';
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
errorBuffer
仅在curl_easy_perform()
返回错误代码时才用有效的字符串填充.
errorBuffer
is only filled with a valid string if curl_easy_perform()
returns an error code.
此外,Uploader::WriteResponce
是C ++函数.在这一行:
Also, Uploader::WriteResponce
is a C++ function. With this line:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteResponce);
CURL希望第三个参数是C语言的指针.在这里,您正在传递一个指向C ++的函数.您需要将对WriteResponce
的调用包装在调用C ++函数的extern "C"
函数中:
CURL expects the third parameter to be a pointer-to-C function. Here, you are passing a pointer-to-C++ function. You need to wrap the call to WriteResponce
in an extern "C"
function that calls the C++ function:
extern "C" size_t call_uploader_writeresponce(char *ptr, size_t size, size_t nmemb, void *user_data) {
return Uploader::WriteResponce(ptr, size, nmemb, static_cast<std::string *>(user_data));
}
// ...
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &call_uploader_writeresponce);
写入功能"需要返回size_t
,而不是int
; Uploader::WriteResponce
需要返回size_t
.
The "write function" needs to return size_t
, not int
; Uploader::WriteResponce
needs to return size_t
.
这篇关于libCurl.继续进行时取消请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!