繁体   English   中英

如何在 libcurl 中使用成员函数指针

[英]How can I use a member function pointer in libcurl

我正在使用 libcurl 我在类中下载文件,我想查看进度函数。 我注意到我可以设置一个典型的函数指针

curl_easy_setopt(mCurl, CURLOPT_PROGRESSFUNCTION, progress_func3);

但是,我想将它设置为指向我的类的函数指针。 我可以得到要编译的代码

curl_easy_setopt(mCurl, CURLOPT_PROGRESSFUNCTION, &MyClass::progress_func3);

并且将调用progress_func3函数。 问题是,一旦它返回,就会出现“检测到缓冲区溢出!” 报错通过,说程序不能安全继续执行,必须终止。 (这是一个 Microsoft Visual C++ 运行时库错误窗口,我使用的是 Visual Studio 2010)。

当我使用函数时,没有问题,但是当我使用成员函数指针时,我会得到这个错误。 如何在 libcurl 中使用成员函数指针?

非静态成员函数需要this指针才能调用。 您不能为这种类型的接口提供this指针,因此不可能使用非静态成员函数。

您应该创建一个“普通 C”函数作为您的回调,并让该函数调用相应MyClass实例上的成员函数。

尝试类似:

int my_progress_func(void *clientp, ...)
{
   MyClass *mc = static_cast<MyClass*>(clientp);
   mc->your_function(...);
   return 0; // or something else
}

然后:

curl_easy_setopt(mCurl, CURLOPT_PROGRESSDATA,     &your_myclass_object);
curl_easy_setopt(mCurl, CURLOPT_PROGRESSFUNCTION, my_progress_func);

(显然,您负责此处的类型匹配。如果您将MyClass指针以外的任何其他内容附加到进度数据,则您自己。)

您可以使用 boost::bind() 来实现这一点。 例如:

boost::bind(&MyClass::progress_func3, this);

是指向返回 void 且没有参数的方法的指针。 如果您的回调需要参数,请按如下方式使用占位符:

boost::bind(&MyClass::progress_func3, this, _1, _2) 

this指针可以替换为指向MyClass实例的指针。

编辑:您应该能够使用相对可互换的 boost::function<> 和 function ptr 类型。 例如:

typedef boost::function< void (int, short) > Callback;

相当于

typedef void (Callback)(int);

您可能需要在它之间添加一个函数来让编译器满意。 我知道我已经使用 boost::function<> 定义了一个回调并传入了一个常规函数指针。

类实例“this”有效:

static int progressCallback( void * p, double dltotal, double dlnow, double ultotal, double ulnow )
{
    QTWindow * w{ static_cast< QTWindow * >( p ) };
    emit w->uploadProgressData( ulnow, ultotal );
    return 0;
}

curl_easy_setopt( curl, CURLOPT_NOPROGRESS, 0L );
curl_easy_setopt( curl, CURLOPT_PROGRESSFUNCTION, progressCallback );
curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, this );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM