以C ++方式将静态writeCallBack函数转换为非静态成员函数的内存问题

时间:2016-12-15 16:30:13

标签: c++11 curl callback

我想在非静态成员函数中实现cURL的写回调函数。

调用此方法时会抛出EXE_BAD_ACCESS错误。但是,如果我在静态方法中使用它,它可以正常工作。

非静态成员函数:

size_t dataFromWebService :: WriteCallback(void *contentsPtr, size_t size, size_t nmemb, string stream, void *classPointer)
{
    std::cout<<"Called write call back" <<std::endl;

    return static_cast<dataFromWebService*>(classPointer)->WriteCallbackImpl(contentsPtr, size, nmemb, stream);        
}

size_t dataFromWebService :: WriteCallbackImpl(void *contentsPtr, size_t size, size_t nmemb, string stream)
{
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = chunk1;//(struct MemoryStruct *)userp;

    mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1);
    if(mem->memory == NULL) {
        /* out of memory! */
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }

    memcpy(&(mem->memory[mem->size]), contentsPtr, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;        
}

我援引了:

std::string myData;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &dataFromWebService::WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &myData);

调试时我得到了:

size    size_t  419      
nmemb   size_t  140734799803520        
realsize    size_t  58967881117674880

等效的静态方法是:

static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp, struct MemoryStruct *myChunk)
{
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = myChunk;//(struct MemoryStruct *)userp;

    mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1);
    if(mem->memory == NULL) {
        /* out of memory! */
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }

    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}

我援引了:

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);

调试值为:

size    size_t  1        
nmemb   size_t  419    
realsize    size_t  2

MemoryStruct:

struct MemoryStruct
{
char *memory;
size_t size;
};

为什么我为相同数据的非静态成员函数获得更大的nmemb值?有什么问题?

0 个答案:

没有答案