Tuesday, July 18

the c++ function pointers

... so ... today I struggled to get some function pointers;

The syntax is a bit weird, and I couldn't remember it since the last time I saw function pointers was when I was reading on the boost library (and that was ... different).

Anyway, here is the problem:

I have some c++ code - pretty straightforward - calling into a method of some object.

like this:
{
  // some c++ code
  object.methodA(paramter1, parameter2);
  // some more c++ code
}

(where object is an instance of - say - MyObject class).
When running it under high loads however, the application crashes, and instead of methodA call on the stack I get some methodB;

Naturally, it's been driving me up the walls.


So, I figured ... "hey let's print the function addresses and make sure they're the same".

So, a function pointer is taken like this:
void function() {};
void (*functionPointer)() = &function;


To make things simple, I typedefed it:
void function() {};
typedef void (*FunctionPtr)();
FunctionPtr functionPointer = &function;



This much, you can find with a search on the net.

What I needed was getting the address of a polimorphic member function, so the next step was to get the address for a member function, and the syntax for that, was as follows (using my code above):


typedef void (MyObject::*FunctionPtr)();
FunctionPtr functionPointer = &MyObject::function;


That covered the "method" part;

I stil had to get one speciffic form of the method.

I found no source on the net for this, but finally I figured it's in the parameters of the pointer declaration.

So, there you go: to get a particular form of the function, this is the code:


class MyObject
{
  void function() {}
  void function(int) {}
}

typedef void (MyObject::*FunctionPtr)();
FunctionPtr functionPointer = &MyObject::function; // will get the first form

typedef void (MyObject::*FunctionPtr)(int);
FunctionPtr functionPointer = &MyObject::function; // will get the second form.


... And this has been my contribution to the bettering of human understanding for this evening.

bye bye,
utnapistim

No comments: