首页 > 解决方案 > 函数为 std::String 返回空值

问题描述

用于从Flask refreshWeb 服务器获取输出结果,当执行该函数时,它会将所需的结果打印到屏幕上,但是当需要打印时,它不会打印输出值,您得到的只是一个空行

为什么会这样



size_t CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::string* s)
{
    size_t newLength = size * nmemb;
    try
    {
        s->append((char*)contents, newLength);
    }
    catch (std::bad_alloc& e)
    {
        //handle memory problem
        return 0;
    }
    return newLength;
}

std::string refresh(std::string path) {
    CURL* curl;
    CURLcode res;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    const char* path_ = path.c_str();
    std::string s;
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, path_);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "out=");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK)
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        }
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    std::cout << s << std::endl;
    return s;
}

驱动程序代码

int main() {
    std::string out = refresh(server_path+"/refresh");
    std::cout << out << std::endl;
} 

标签: c++curl

解决方案


推荐阅读