Passing a string to a callback function

Started by
2 comments, last by Cygon 15 years, 11 months ago
Hello Maybe you could help me with this. I have this function Function(void(COpenGL::*Callback)()); what i want to do is to pass to this function a string. so im thinking something like this string funcString = "COpenGL::NeededFunc"; std::stringstream ss; ss << funcString; void* value; ss >> value; Function(value); well of course this doesnt work - now comes my question - is there another way to what i need - or maybe this is the way but im doing it wrong. Can you help me? Thanks!
Advertisement
Just modify you callback signature to include a string argument. In the simplest case:

#include <iostream>typedef void CallbackFunction(const std::string &);void Test(CallbackFunction *callback) {  callback("Hello World");}void MyCallback(const std::string &someString) {  std::cout << someString << std::endl;}int main() {  Test(&::MyCallback);}


If your intention is to do a callback to a method (it seems so), just do the same for the method callback signature:

class COpenGL {  void (COpenGL::*callback)(const std::string &);    void myCallback1(const std::string &someString) {    std::cout << "MyCallback1: " << someString << std::endl;  }  void myCallback2(const std::string &someString) {    std::cout << "MyCallback2: " << someString << std::endl;  }  void test() {    this->callback = &COpenGL::myCallback1;    (this->*callback)("Hello World");    this->callback = &COpenGL::myCallback2;    (this->*callback)("Hello World");  }};


Hope that helps!
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
Thanks - i decided to do a stl map - and asociate a function to a string - its suite what i need
Ah, so you wanted to call a function by name. Sorry, I totally misunderstood your intention.

Your map<> is the right way to go. C++ doesn't support reflection, so creating a name lookup yourself is the only possible solution.
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.

This topic is closed to new replies.

Advertisement