Monday, 15 July 2013

c++ - std::function.target returns null -



c++ - std::function.target returns null -

i'm using curl download files on http. curl requires callback handle data, have callback in class , i'm using combination of std::bind , std::function create function proper type.

size_t networkresource::writefunction(char *ptr,size_t size,size_t nmemb,void *userdata) { ... } void networkresource::loadfunction(void) { using namespace std::placeholders; typedef size_t curlcallback(char*,size_t,size_t,void*); auto function=std::function<curlcallback>(std::bind(&networkresource::writefunction,this,_1,_2,_3,_4)).target<curlcallback*>(); curl *curl=curl_easy_init(); curlcode err; ... err=curl_easy_setopt(curl,curlopt_writedata,nullptr); if(err!=curle_ok) std::cout<<curl_easy_strerror(err)<<std::endl; err=curl_easy_setopt(curl,curlopt_writefunction,*function); if(err!=curle_ok) std::cout<<curl_easy_strerror(err)<<std::endl; ... }

the problem function null. according documentation, happens when returned type doesn't match target type of function, far can tell match.

auto function = std::function<curlcallback>( std::bind(&networkresource::writefunction,this, _1,_2,_3,_4)).target<curlcallback*>();

the std::function object you're constructing destroyed @ end of look above, , variable function would've pointed invalid memory, had phone call std::function::target worked intended. in case, doesn't , function phone call returns nullptr.

this because target function type of std::function not same type of curlcallback. this example shows case phone call works, , 1 fails.

your problem can solved without utilize of std::function altogether.

according documentation curl_easy_setopt, when sec argument curlopt_writefunction, 3rd argument should pointer function having signature

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

the lastly argument userdata can set via phone call curlopt_writedata. utilize pass pointer networkresource instance (the this pointer).

as write_callback, create static fellow member function performs functionality need.

class networkresource { // ... static size_t writefunction(char *ptr,size_t size,size_t nmemb,void *userdata); }; size_t networkresource::writefunction(char *ptr,size_t size,size_t nmemb,void *userdata) { // userdata points networkresource instance auto res = static_cast<networkresource *>(userdata); // utilize res , remaining function arguments handle phone call } void networkresource::loadfunction(void) { curl *curl=curl_easy_init(); curlcode err; ... err=curl_easy_setopt(curl,curlopt_writefunction,&networkresource::writefunction); if(err!=curle_ok) std::cout<<curl_easy_strerror(err)<<std::endl; err=curl_easy_setopt(curl,curlopt_writedata,static_cast<void *>(this)); if(err!=curle_ok) std::cout<<curl_easy_strerror(err)<<std::endl; ... }

c++ c++11 curl

No comments:

Post a Comment