Using a C ++ function pointer as a signal handler.

I want to add a new handler to signal SIGUSR1 in my code. here's signal

the signature header file signal.h

:

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

My handler is a member function, so I use std::bind

to make the function match the accepted input signal

.

myclass::my_handler(int x);

      

Here's my conversion from member function to signal

accepted input:

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

      

However, it std::bind

returns a C ++ representation of a function pointer (aka std::function<void(int)>

) and I need a C representation that is (void)(*)(int)

.

Should I do the casting by force or maybe a C ++ alternative for signal

?

thank

+3


source to share


2 answers


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

What you can do is declare a global variable cpphandler as -

std::function<void(int)> cpphandler = NULL;

      

Also declare the function as -

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

      



Now in the function where you want to create the do binding -

cpphandler = std::bind(&myclass::my_handler, this, std::placeholders::_1); 
signal(x, signal_handler); //replace x with whatever signal you want to install 

      

This ensures that the function signal_handler

is created using the C ABI. And calls the C ++ function code from the C ++ ABI.

You can now use the function signal

with signal_handler

.

+2


source


Since you are using a C ++ compiler, I suggest that you simply define a normal function that calls your member function handler:

void signal_handler_wrapper(int x)
{
   myclass::my_handler(x);
}

      



Then in your main code:

signal(SIGINT, signal_handler_wrapper);

      

0


source







All Articles