C++ libcurl returning null?



我是c++的新手,需要在类中实现请求。但我得到的答案是零。从我一直在研究,这是一个问题与静态WriteCallback函数。但我不能解决这个问题,我怎么能解决它?

class AbstractInstanceParser
{
public:
static size_t WriteCallback(char *contents, size_t size, size_t nmemb, char *buffer_in)
{
((std::string *)buffer_in)->append((char *)contents, size * nmemb);
return size * nmemb;
}
bool parse()
{
CURL *curl = curl_easy_init();
CURLcode res;
Json::Value json;
Json::Reader reader;
double distance;
std::string readBuffer;
auto ok = parse_impl();
if (!ok)
{
return ok;
}
auto matrix_size = static_cast<int>(demands.size());
costs_matrix.resize(matrix_size, matrix_size);
for (auto i = 0; i < matrix_size - 1; i++)
{
costs_matrix.at(i, i, 0.0f);
for (auto j = i + 1; j < matrix_size; j++)
{
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5000/route/v1/driving/" + std::to_string(x_coordinates[i]) + "," + std::to_string(y_coordinates[i]) + ";" + std::to_string(x_coordinates[j]) + "," + std::to_string(y_coordinates[j]) + "?annotations=distance");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
reader.parse(readBuffer, json);
distance = json["routes"][0]["distance"].asFloat();
std::cout << distance << std::endl;
}
costs_matrix.at(i, j, distance);
if constexpr (round_costs)
{
costs_matrix.at(i, j, std::round(costs_matrix.at(i, j)));
}
costs_matrix.at(j, i, costs_matrix.at(i, j));
}
}
curl_easy_cleanup(curl);
...
...
...

我以这种方式在类外运行libcurl,它工作得很好,但在类内,它不起作用。

不允许将std::string的值传递给curl_easy_setopt(curl, CURLOPT_URL, ...);

你做了什么(我改变了你的很长很难读的行):

const std::string url = "http://localhost:5000/route/v1/driving/" +
std::to_string(x_coordinates[i]) + "," + std::to_string(y_coordinates[i]) +
";" + std::to_string(x_coordinates[j]) + "," +
std::to_string(y_coordinates[j]) + "?annotations=distance";
curl_easy_setopt(curl, CURLOPT_URL, url);

你想做什么:

const std::string url = "http://localhost:5000/route/v1/driving/" +
std::to_string(x_coordinates[i]) + "," + std::to_string(y_coordinates[i]) +
";" + std::to_string(x_coordinates[j]) + "," +
std::to_string(y_coordinates[j]) + "?annotations=distance";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
//                                      ^^^^^^^

最新更新