Sign in to follow this  
guvidu

Passing a string to a callback function

Recommended Posts

guvidu    102
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!

Share this post


Link to post
Share on other sites
Cygon    1219
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!

Share this post


Link to post
Share on other sites
Cygon    1219
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this