简体   繁体   中英

Send to server float array using libcurl c++

I am using a portaudio callback where I receive periodically a buffer of audio and store it on main_buffer . I only set the settings bellow for curl and only use the CURLOPT_POSTFIELDS to set the float buffer before sending it with curl_easy_perform . On the server side I am using python django:

float main_buffer[256];

url_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, URL);

//portaudio periodic callback
callback(){
  //...
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, main_buffer);
  curl_easy_perform(curl);
}

The request received in server has no content inside body. How to send main_buffer the right way?

Thank you !

What you need to do is to serialise the data that you send, and then deserialise what you receive. There is no "the right way". There are several ways with different advantages.

In your case, I recommend starting with a simple way. Simplest portable way to serialise floating point is to use textual encoding. A commonly used textual format that can represent arrays is JSON. For example, the array float[] main_buffer{1.0f, 1.5f, 2.0f} could be encoded as [1.0,1.5,2.0] .

The reading part in Python is quite simple:

json.loads(request.body.decode('utf-8'));

The writing part in C++ is a bit more complex. There is no standard way to encode JSON in C++. You can use a full encoder based on the specification , or you could write an ad-hoc loop for this specific case:

std::stringstream ss;
ss << '[';
const char* separator = "";
for (float f : main_buffer) {
    ss << separator << f;
    separator = ",";
}
ss << ']';
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ss.str().c_str());
curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM