0

Found some user attempts to invoke a member function pointer from a void pointer.

e.g., How to call a class member function from 2 void pointers

I would like to test it on my project, but the topics enclosed are too advanced for me and the questions usually hold partial code only.

Looking for a simple working example I could test upon.

Edit: I am trying to create a callback mechanism on my system. so I can pass different types of callback functions without using wrapper functions or static member functions

schanti schul
  • 681
  • 3
  • 14
  • 1
    Describe your problem in your question itself instead of giving a link to a question which is related to yours. Do you have any code that you're using? If yes, which in which part you're facing the problem. A [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) might also help. – Jason Aug 21 '22 at 10:32
  • 1
    You cannot do *anything* with a void pointer apart from passing it around as pointer value or casting it back to some more appropriate type. So whatever you actually want to do with, it will involve these two actions. – Aconcagua Aug 21 '22 at 10:36
  • Are you after something like this: `template R invoke(void* object, R(T::*mf)(A ...), A&& ... a) { return (static_cast(object)->*mf)(std::forward(a)...); }` (untested)? – Aconcagua Aug 21 '22 at 10:40
  • `I am trying to create a callback mechanism on my system. so I can pass different types of callback functions without using wrapper functions or static member functions` - have you considered template functions already? – The Dreams Wind Aug 21 '22 at 11:01
  • 1
    Have you considered [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function) already? You could combine with lambdas. That would from a coding point of view be the most simple approach – possibly, though, not the most efficient one. – Aconcagua Aug 21 '22 at 11:14
  • If you store target object and and member function both as some kind of generic pointers (`void*` only for the object to call upon – member function pointers you *cannot*, so you need to think up something different!) you need a way to get the original types back from those. I did something similar once, but didn't get around some separate function doing that, which needed to be stored in yet another (normal) function pointer. – Aconcagua Aug 21 '22 at 11:15
  • Beware of UB: https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Aug 21 '22 at 12:41

0 Answers0