Function Pointer

Hey,

I have a header file with this line of code:

extern "C" void amqC_dataInit(const char *uri, const char *channel,int (*cb_MessageReceived)(const TRANSFERDATA_FULL * dataToSend,const char action),int useTopics,FILE * logfile);


In C I can use this code like this:

1
2
3
4
int receiveData(const TRANSFERDATA_FULL * sendData, const char action) {
	fprintf(stdout, "LSPI = %s", sendData->lsph);fflush(stdout);
	return 0;
}



In the main file i place this line:

amqC_dataInit("foo","test",&receiveData,1,stdout);


this compiles and works perfectly

In C++ I have this code:

Header file:

1
2
3
4
5
6
7
8
9
class Test {
	private:
		int messageReceived(const TRANSFERDATA_FULL * sendData, const char action);
	public:
		Test();
		virtual ~Test();
		bool initialize();
		bool stop();
	};

cpp file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	Test::Test() {
	}

	Test::~Test() {
	}

	bool Test::initialize() {
		amqC_dataInit(this->m_ActiveMQUri.c_str(), this->m_ActiveMQUri.c_str(), &Test::messageReceived, 0, stdout);
		return true;
	}

	bool Test::stop() {
		return true;
	}

	int Test::messageReceived(const TRANSFERDATA_FULL * sendData, const char action) {

	}


This gives me the compile error:

error: cannot convert ‘int (hms::Test::*)(const TRANSFERDATA_FULL*, char)’ to ‘int (*)(const TRANSFERDATA_FULL*, char)’ for argument ‘3’ to ‘void amqC_dataInit(const char*, const char*, int (*)(const TRANSFERDATA_FULL*, char), int, FILE*)’
make: *** [src/Test.o] Error 1


The only difference I see is the hms::Test:: (The namespace and the class name).

Am I not seeing something, or is this just not possible?

Thankx in advance.
Jan
Not the best one @ function pointers here, but I think it should be Test::messageReceived instead of &Test::messageReceived.

But I think that is just one part of it. I believe you are trying to use a function pointer of a non-static function as a regular C pointer. I think this is not allowed. But again, I'm not the brightest fellow for function pointers.
Yes to the second part. Pointers to member functions are different than pointers to free functions because of the implicit "this" pointer.
closed account (S6k9GNh0)
The use of Boost.Bind or the upcoming std::bind can be used to bind member functions into a simple (non-)nullary function. They simplify what you're trying to do. I suggest you look it up. Please be warned though that the errors produced by bind are horrendous and takes patience. You may be better off simply creating a cleaner solution.

As to whether you should use Boost.Bind or std::bind, I'd use Boost.Bind for current portability sake.
Last edited on
However, neither boost::bind nor std::bind will solve OP's problem. Once a C function pointer, always a C function pointer.
closed account (S6k9GNh0)
I forgot to suggest boost::function.
Topic archived. No new replies allowed.