Ishmael
12th January 2011, 21:29
I'm trying to get a libcurl script to run under Windows. I know about QNetworkRequest, but I would just like to get this working, if possible. It works fine under Linux.
For some reason, the first time the WriteMemoryCallback function is called, data is written as expected. However, on subsequent call to the same function, new data does not get appended to the array after a realloc. Any idea what is going on? Thanks for your help!
Copying straight from the example provided by the libcurl folks:
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); // Rather than writing to a file, keep data in memory
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
printf("not enough memory (realloc returned NULL)\n");
exit(EXIT_FAILURE);
}
memcpy(&(mem->memory[mem->size]), ptr, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
// THIS IS CORRECT
qDebug()<<"Bytes received:";
qDebug()<<QString::fromUtf8((char *)ptr);
// NEW DATA DID NOT GET APPENDED!
qDebug()<<"Bytes in memory:";
qDebug()<<QString::fromUtf8(mem->memory);
return realsize;
}
In my .h file, I have:
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data);
class MainWindow : public QMainWindow
{
Q_OBJECT
etc.
For some reason, the first time the WriteMemoryCallback function is called, data is written as expected. However, on subsequent call to the same function, new data does not get appended to the array after a realloc. Any idea what is going on? Thanks for your help!
Copying straight from the example provided by the libcurl folks:
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); // Rather than writing to a file, keep data in memory
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
printf("not enough memory (realloc returned NULL)\n");
exit(EXIT_FAILURE);
}
memcpy(&(mem->memory[mem->size]), ptr, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
// THIS IS CORRECT
qDebug()<<"Bytes received:";
qDebug()<<QString::fromUtf8((char *)ptr);
// NEW DATA DID NOT GET APPENDED!
qDebug()<<"Bytes in memory:";
qDebug()<<QString::fromUtf8(mem->memory);
return realsize;
}
In my .h file, I have:
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data);
class MainWindow : public QMainWindow
{
Q_OBJECT
etc.