12
class Filter{
private:
    string contents;
    bool Server(void);
public:
    void handle(void *, size_t, size_t, void *);
   };

i have a class header like this. i want to call curl WRITEFUNCTION inside the function Server which would use handle to write to the string contents. although it keeps giveng me the error

error: invalid use of member (did you forget the ‘&’ ?)

the line pointed by error is that of CURLOPT_WRITEFUNCTION.... My curl request looks something like this...

curl_easy_setopt(curl,CURLOPT_URL, address.c_str());
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle);
curl_easy_perform(curl);

that means its unable to access the handle().. how can i rectify this?

Prasanth Madhavan
  • 12,657
  • 15
  • 62
  • 94

3 Answers3

19

handle must be a static member function. You can pass a pointer to the instance of Filter as last argument by using CURLOPT_WRITEDATA

class Filter
{ 
private:
    std::string content_;
    static size_t handle(char * data, size_t size, size_t nmemb, void * p);
    size_t handle_impl(char * data, size_t size, size_t nmemb);
};

size_t Filter::handle(char * data, size_t size, size_t nmemb, void * p)
{
    return static_cast<Filter*>(p)->handle_impl(data, size, nmemb);
}

size_t Filter::handle_impl(char* data, size_t size, size_t nmemb)
{
    content_.append(data, size * nmemb);
    return size * nmemb;
}

int main()
{
   // curl initialization... should be done in a constructor
   Filter f;
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, &f);
   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &Filter::handle);
   // curl cleanup... should be done in a destructor
   return 0;
}
hansmaad
  • 18,417
  • 9
  • 53
  • 94
3
string temp;

curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle);
curl_easy_setopt(curl,CURLOPT_WRITEDATA,&temp);

size_t Filter::handle(void *ptr, size_t size, size_t nmemb, string stream)
{
    string temp(static_cast<const char*>(ptr), size * nmemb);
    stream = temp;
    return size*nmemb;
}

thats how i got it to work.. this will save the website to the string named temp.

Prasanth Madhavan
  • 12,657
  • 15
  • 62
  • 94
  • 1
    This creates a local std::string temp where the data is stored. Then temp is copied to the argument stream. When the funcdtion returns, both strings will be deleted. Use temp.append(...) instead to write data to the global string temp. Or use correct signature with a pointer to the global string and call append through this pointer. – hansmaad Nov 19 '10 at 18:12
  • You should use append because the write function could be called multiple times for one resource you#re loading. – hansmaad Nov 19 '10 at 18:17
1

I am using curlpp:

std::stringstream result;

request.setOpt(cURLpp::Options::WriteStream(&result));
request.perform();

this will save the reply webserver to the stringstream named result.

TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130
cheshir
  • 71
  • 1
  • 3