Zohar81 Zohar81 - 3 years ago 91
C Question

Using c++ function pointer as signal handler.

I'd like to add new handler to signal SIGUSR1 in my code. here's

signal
signature form header file
signal.h
:

void (*signal(int, void (*)(int)))(int);


My handler is a member function, so I'm using
std::bind
to make the function fit in
signal
accepted input.

myclass::my_handler(int x);


Here's my conversion of the member function to
signal
accepted input:

std::bind(&myclass::my_handler, this, std::placeholders::_1);


However,
std::bind
return the c++ representation of function pointer (a.k.a
std::function<void(int)>
) and I need the C representation which is
(void)(*)(int)
.

Should I do the casting forcefully, or perhaps there's c++ alternative for
signal
?

Thanks

Answer Source

There is no portable way to convert a C++ function to a C function because they can have different ABIs.

What you can do is this

auto cpphandler = std::bind(&myclass::my_handler, this, std::placeholders::_1); 

extern "C" {
    void signal_handler(int i);
}
void signal_handler(int i){
    cpphandler(i);
    return;
}

This makes sure that the function signal_handler is created with C ABI. And calls the C++ function code with C++ ABI.

Now you can use the signal function with signal_handler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download