libCurl. Cancel request while proceed

本秂侑毒 提交于 2019-12-25 17:02:15

问题


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.


回答1:


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.

For example, this line is incorrect:

curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);

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.

Use this instead:

char errorBuffer[CURL_ERROR_SIZE + 1]; errorBuffer[CURL_ERROR_SIZE] = '\0';
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);

errorBuffer is only filled with a valid string if curl_easy_perform() returns an error code.

Also, Uploader::WriteResponce is a C++ function. With this line:

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteResponce);

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);

The "write function" needs to return size_t, not int; Uploader::WriteResponce needs to return size_t.



来源:https://stackoverflow.com/questions/7400127/libcurl-cancel-request-while-proceed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!