如何在杯子中使用类方法?
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);
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 检查类方法中是否(此 == nullptr)
- 从基类实例调用派生类方法而不进行强制转换
- 函数从唯一代码调用正确的子类方法
- C++ - 如何在不静态的情况下将回调绑定到类方法?
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- C++:从属性类调用顶级类方法