如何在杯子中使用类方法?

How to use a class method in cupsEnumDests?

本文关键字:类方法      更新时间:2023-10-16

我正在启动一个将使用 CUPS C API 的程序,第一个示例是调用cupsEnumDests函数:

#include <stdio.h>
#include <cups/cups.h>
int print_dest(void *user_data, unsigned flags, cups_dest_t *dest)
{
if (dest->instance)
printf("%s/%sn", dest->name, dest->instance);
else
puts(dest->name);
return (1);
}
int main(void)
{
cupsEnumDests(CUPS_DEST_FLAGS_NONE, 1000, NULL, 0, 0, print_dest, NULL);
return (0);
}

但是这个函数将 C 函数作为参数,而我正在使用 C++ 并且我想为它提供一个类方法。

我尝试了cupsEnumDests(CUPS_DEST_FLAGS_NONE, 1000, NULL, 0, 0, this->MyMethod, NULL);但它给出了错误

错误:无效使用非静态成员函数"int MyClass::MyMethod(void*, unsigned int, cups_dest_t*(">

更新我发现当我使方法static时它确实有效,但我想使用this->MyMethod.

无法将非静态类成员函数转换为常规函数指针。 解决此问题的常见方法(API 允许(是传递一个采用void*的函数指针,然后将可选数据作为void*传递给 API 函数,然后函数将该void*转换为类类型并调用其成员函数。

这将使您的代码看起来像

struct Foo
{
void some_function() { /* do stuff */ }
};
int wrapper_func(void* instance, unsigned flags, cups_dest_t *dest)
{
static_cast<Foo*>(instance)->some_function();
return 42;
}
int main(void)
{
Foo f;
cupsEnumDests(CUPS_DEST_FLAGS_NONE, 1000, NULL, 0, 0, wrapper_func, &f);
}