Connecting Tech Pros Worldwide Help | Site Map

Using C function pointer with c++ member func pointer

myusernotyours's Avatar
Familiar Sight
 
Join Date: Nov 2007
Posts: 168
#1: 4 Weeks Ago
Hello everyone.

I am using a C library from C++ code. The C library declares some function pointers using typedef, and then makes some variables using this function pointer as the type. Like:
Expand|Select|Wrap|Line Numbers
  1. typedef void (*func) (int);
  2. //then the pointer...
  3. func ptr;
  4.  
For me to work with this library I need to assign one of my member functions to the library variable(the func pointer) above.
My member function's declaration is similar to the C, but it's not static nor global(I don't want to make it so).

I take the address of the member function Inside my constructor like:
Expand|Select|Wrap|Line Numbers
  1. class Mine{
  2. public:
  3. Mine(){ func = &Mine::myfunc;} //This won't work!
  4. void myfunc(int i){}
  5. }
  6.  
but I can't assign it to the C func pointer variable (declared in the library header). The compiler complains about the types being different. Am using g++ on mingw/windows.

Is there a way out or do I have to use some other technique?

Regards,

Alex.
best answer - posted by Banfa
Quote:

Originally Posted by myusernotyours View Post

but it's not static nor global(I don't want to make it so).

Unfortunately you have no choice. A member function has an implicit this parameter that is passed into the function which allows the class member functions to access the class data.

C can never create the this pointer, it has no knowledge or concept of classes. You will have to pass your C library either a global or a static member function and then arbitrate for yourself which object was the target when the function is called.
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,158
#2: 4 Weeks Ago

re: Using C function pointer with c++ member func pointer


Quote:

Originally Posted by myusernotyours View Post

but it's not static nor global(I don't want to make it so).

Unfortunately you have no choice. A member function has an implicit this parameter that is passed into the function which allows the class member functions to access the class data.

C can never create the this pointer, it has no knowledge or concept of classes. You will have to pass your C library either a global or a static member function and then arbitrate for yourself which object was the target when the function is called.
myusernotyours's Avatar
Familiar Sight
 
Join Date: Nov 2007
Posts: 168
#3: 4 Weeks Ago

re: Using C function pointer with c++ member func pointer


Thanks, Banfa. I think static it will be then.

Regards,

Alex
Reply