Sign in to follow this  

Passing a string to a callback function

This topic is 3500 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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

This topic is 3500 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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