Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class member function and callback from C API

I am trying to learn how to call this write_data(…) function from the funmain() function in the class as shown in the code bellow. (I know this program works if I just list these two functions without putting it inside a class).

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data) line gives me error and wouldn’t let me call the write_data(…) function. Can you please correct my code and tell me how I can achieve this. Any help would be greatly appreciated. Thanks.

error C3867: 'go_website::write_data': function call missing argument list; use '&go_website::write_data' to create a pointer to member

//Microsoft Visual Studio 10 in C++
#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <iostream>
#include <curl/easy.h>
#include <string>
using namespace std;

extern "C" typedef size_t curl_write_callback(void *ptr, size_t size, size_t nmemb, FILE *stream);
class go_website
{
public:
static curl_write_callback write_data;

void funmain()
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://www.shorturl.com/";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data); 
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
}};

extern "C" size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) 
{
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}

int main()
{
   go_website a;
   a.funmain();
   return 0;
}
like image 649
Learner_51 Avatar asked Dec 13 '22 05:12

Learner_51


1 Answers

It is possible http://curl.haxx.se/docs/faq.html#Using_C_non_static_functions_f

 // f is the pointer to your object.
 static YourClass::func(void *buffer, size_t sz, size_t n, void *f)
 {
   // Call non-static member function.
   static_cast<YourClass*>(f)->nonStaticFunction();
 }
 // This is how you pass pointer to the static function:
 curl_easy_setopt(hcurl, CURLOPT_WRITEFUNCTION, YourClass:func);
 curl_easy_setopt(hcurl, CURLOPT_WRITEDATA, this);
like image 105
Evalds Urtans Avatar answered Dec 30 '22 15:12

Evalds Urtans