I would like to wrap a Linux System Call API (clone) into a C++ class.
However, this API required a function pointer, and it's parameter list is fixed, for instance:
typedef int (*callback)(void *);
void system_call(callback f) {
void *t = nullptr;
f(t);
}
Now, My class like:
class Foo {
public:
void start() {
// WRONG: cannot pass non-static member function due to pointer `this`
system_call(this->foo);
}
private:
int foo(void *args) {
f->necessary();
return 0;
}
void necessary() {
std::cout << "call success!!!" << std::endl;
}
};
int main() {
Foo obj;
obj.start();
}
So, the important problems are:
- system_call's parameter are fixed and unchangeable.
- the method
start()
must be non-static.
I was thinking about this, by using a static member:
class Foo {
public:
void start() {
auto func = std::bind(foo, std::placeholders::_1, this);
system_call(func); // WRONG: cannot convert std::_Bind to a function pointer
}
private:
static int foo(void *args, Foo *f) {
f->necessary();
return 0;
}
void necessary() {
std::cout << "call success!!!" << std::endl;
}
};
or this, by using lambda with captures:
class Foo {
public:
void start() {
auto func = [this](void *args) -> int {
this->necessary();
};
system_call(func); // WRONG: cannot convert a lambda with captures to a function pointer
}
private:
void necessary() {
std::cout << "call success!!!" << std::endl;
}
};
They all wrong.
Any solutions to fix this problem?
P.S. I think this is a huge requirements for encapsulation, but here I found some answers are not elegant (they modified the parameter list, not possible for system call):