Contents Up << >>

How do I pass a ptr to member fn to a signal handler, X event callback, etc?

Don't.

Because a member function is meaningless without an object to invoke it on, you can't do this directly (if The X Windows System was rewritten in C++, it would probably pass references to objects around, not just pointers to fns; naturally the objects would embody the required function and probably a whole lot more).

As a patch for existing software, use a top-level (non-member) function as a wrapper which takes an object obtained through some other technique (held in a global, perhaps). The top-level function would apply the desired member function against the global object.

E.g., suppose you want to call Fred::memfn() on interrupt:

  	class Fred {
	public:
	  void memfn();
	  static void staticmemfn();	//a static member fn can handle it
	  //...
	};

	//wrapper fn remembers the object on which to invoke memfn in a global:
	Fred* object_which_will_handle_signal;
	void Fred_memfn_wrapper() { object_which_will_handle_signal->memfn(); }

	main()
	{
	  /* signal(SIGINT, Fred::memfn); */   //Can {\it not} do this
	  signal(SIGINT, Fred_memfn_wrapper);  //Ok
	  signal(SIGINT, Fred::staticmemfn);   //Also Ok
	}
Note: static member functions do not require an actual object to be invoked, so ptrs-to-static-member-fns are type compatible with regular ptrs-to-fns (see ARM ["Annotated Reference Manual"] p.25, 158).