C++ Segmentation Fault caused by global variable in separate source file

前端 未结 1 589
醉话见心
醉话见心 2021-01-27 14:39

I\'m a c++ noob trouble shooting for 4 hours now. I am getting my first segmentation fault. I think it is coming from the variable data. The program pulls the html (using cUR

相关标签:
1条回答
  • 2021-01-27 15:31

    I'm fairly sure this is what you're missing. you can't pass a member function as a callback, as the caller has no clue how to appropriately push this as the first parameter.

    But you can do this:

    class curlbar
    {
    private:
        // callback version used for curl-write-function
        static size_t writeContents_s(char *buf, size_t size, size_t nmemb, void *up)
        {
            curlbar* pThis = static_cast<curlbar*>(up);
            return pThis->writeContents(buf, size, nmemb);
        }
    
    public:
        std::string data;
    
        // member version
        size_t writeContents(char* buf, size_t size, size_t nmemb)
        {
            std::copy(buf, buf+(size*nmemb), std::back_inserter(data));
            return size*nmemb;
        }
    
        void getThreads()
        {
            CURL* curl;
            curl_global_init(CURL_GLOBAL_ALL);
            curl = curl_easy_init();
    
            curl_easy_setopt(curl, CURLOPT_URL, "www.somewebsiteblahblah.com");
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curlbar::writeContents_s);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); // NOTE ADDITION
            curl_easy_setopt(curl, CURLOPT_VERBOSE,1L); //tell curl to output its progress
            curl_easy_perform(curl);
            curl_easy_cleanup(curl);
            curl_global_cleanup();
        }
    };
    

    Given a curlbar obj; object, you invoke it as

    curlbar obj;
    obj.getThreads();
    

    How It Works

    This uses the user-defined data parameter option of an easy-curl handle to establish the piece-o-data that will be send back along with your static writer-callback. That data is provided as the void *up parameter to the callback. So we pass the pointer this and in the static callback use a static_cast to give us an object pointer, pThis. We use that pointer to fire the member function of a similar name, but no longer needing the up param.

    0 讨论(0)
提交回复
热议问题