Elberer
Elberer

Reputation: 11

Writing buffer to BYTE* using CURL

How to write a request buffer to a variable of type BYTE*? I have alreay tried the write own func CURLOPT_WRITEFUNCTION - https://pastebin.com/UBrp7Wyx and set the CURLOPT_WRITEDATA to

BYTE* raw_data = nullptr;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &raw_data);

Upvotes: 1

Views: 1373

Answers (2)

Moshe Groot
Moshe Groot

Reputation: 121

Actually, why you need to store BYTE type? If you want to use CURL for websites and want to accept some extended symbols (like cyrillic), you will not get expected behaviour (for example, UTF-8 has backward compatibility with ASCII, so simple reinterpret or +128 to each symbol will not help). It will have same behaviour as if you converting some char buffer to something else.

So code like this with simple chars work fine:

...

// yours write_function
size_t curlWriteFunc(char* data, size_t size, size_t nmemb,  std::string* buffer)
{
    size_t result = 0;

    if (buffer != NULL)
    {
        buffer->append(data, size * nmemb);
        result = size * nmemb;
    }
    return result;
}

int main()
{
   ... // some prepares, setting up easy_handler and so on

   std::string buffer;

   // set up write function and pointer to buffer
   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curlWriteFunc);
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);

   ... // make request and other things
}

However, if you are using CURL not for websites but for own client, which recives some binary data and BYTE is required, you will have to use some own struct which contains BYTE *, controls allocated size and reallocate memory if needed... Or just use vector<BYTE>.

Upvotes: 1

Botje
Botje

Reputation: 31020

You need a data structure to accumulate data as it comes in, a std::string suffices for that.

At the end, you can then simply do: (assuming you have a std::string s)

BYTE * raw_data = (BYTE *)s.data();

Note that the raw_data pointer is only valid for as long as the string is alive. If you need to contents to survive for longer than that, use a heap allocation and memcpy:

BYTE * raw_data = new BYTE[s.size()];
memcpy(raw_data, s.data(), s.size());

Note that you need to delete[] raw_data yourself at some point.

Upvotes: 0

Related Questions