473,785 Members | 2,488 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing Member Functions as Function Pointers

cps
Hi,

I'm a C programmer taking my first steps into the world of C++.

I'm currently developing a C++ 3D graphics application using GLUT
(OpenGL Utility Toolkit written in C) for the GUI components.

The application is built around a "World" object that contains a "GUI"
object that is a C++ wrapper around GLUT. What I'd like to do is pass a
pointer to a member function in the World class to function in the GUI
class.

Here are the functions I'd like to pass:
void World::Display( )
{
/* clear all pixels */
glClear(GL_COLO R_BUFFER_BIT);

Do OpenGL stuff...
}

void World::Keyboard (unsigned char key, int x, int y)
{
cout << key << endl;

Handle keyboard...
}
I'd like to pass these functions to the constructor of the GUI object
as follows:
p_GUI = new GUI(Display, Keyboard);
I'm getting the following error:

World.cpp(16) : error C2664: 'GUI::GUI(void (__cdecl *)(void),void
(__cdecl *)(unsigned char,int,int))' : cannot convert parameter 1 from
'void (void)' to 'void (__cdecl *)(void)'
None of the functions with this name in scope match the target
type

I understand that (__cdecl *) is a calling convention. What I can't
figure out is how to fix the syntax so that the code compiles.

Any help with this (especially a simple example) would be very much
appreciated.

Cheers,

Chris

Mar 17 '06 #1
11 4432

"cps" <cs******@qub.a c.uk> wrote in message
news:11******** *************@i 39g2000cwa.goog legroups.com...
Hi,

I'm a C programmer taking my first steps into the world of C++.

I'm currently developing a C++ 3D graphics application using GLUT
(OpenGL Utility Toolkit written in C) for the GUI components.

The application is built around a "World" object that contains a "GUI"
object that is a C++ wrapper around GLUT. What I'd like to do is pass a
pointer to a member function in the World class to function in the GUI
class.

Here are the functions I'd like to pass:
void World::Display( )
{
/* clear all pixels */
glClear(GL_COLO R_BUFFER_BIT);

Do OpenGL stuff...
}

void World::Keyboard (unsigned char key, int x, int y)
{
cout << key << endl;

Handle keyboard...
}
I'd like to pass these functions to the constructor of the GUI object
as follows:
p_GUI = new GUI(Display, Keyboard);
I don't see your definition of GUI::GUI anywhere. What are your constructor
parms?
I'm getting the following error:

World.cpp(16) : error C2664: 'GUI::GUI(void (__cdecl *)(void),void
(__cdecl *)(unsigned char,int,int))' : cannot convert parameter 1 from
'void (void)' to 'void (__cdecl *)(void)'
None of the functions with this name in scope match the target
type

I understand that (__cdecl *) is a calling convention. What I can't
figure out is how to fix the syntax so that the code compiles.

Any help with this (especially a simple example) would be very much
appreciated.

Cheers,

Chris

Mar 18 '06 #2
cps
Here they are:
// GUI.h

#ifndef GUI_H
#define GUI_H

class GUI
{
public:
GUI();
GUI(void (*displayFuncti onPtr)(), void
(*keyboardFunct ionPtr)(unsigne d char key, int x, int y));
~GUI();

private:
};

#endif
GUI::GUI(void (*displayFuncti onPtr)(), void
(*keyboardFunct ionPtr)(unsigne d char key, int x, int y))
{
int argc = 0;
char* argv[30];

glutInit(&argc, argv);
glutInitDisplay Mode(GLUT_DOUBL E | GLUT_RGB);
glutInitWindowS ize(250, 250);
glutInitWindowP osition(100, 100);
glutCreateWindo w("Test");
glClearColor(0. 0, 0.0, 0.0, 0.0);
glShadeModel(GL _FLAT);
glMatrixMode(GL _PROJECTION);
glLoadIdentity( );
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glutDisplayFunc (displayFunctio nPtr);
glutIdleFunc(di splayFunctionPt r);
glutKeyboardFun c(keyboardFunct ionPtr);
glutMainLoop();
}

Mar 18 '06 #3
"cps" <cs******@qub.a c.uk> wrote in message
news:11******** *************@i 39g2000cwa.goog legroups.com...
Hi,

I'm a C programmer taking my first steps into the world of C++.


Please see the FAQ:
http://www.parashift.com/c++-faq-lit...o-members.html

- Paul

Mar 18 '06 #4

cps wrote in message ...
Here they are:
// GUI.h
#ifndef GUI_H
#define GUI_H
class GUI{ public:
GUI();
GUI(void (*displayFuncti onPtr)(), void
(*keyboardFunct ionPtr)(unsigne d char key, int x, int y));
~GUI();
private:
};
#endif

GUI::GUI(voi d (*displayFuncti onPtr)(), void
(*keyboardFunct ionPtr)(unsigne d char key, int x, int y)){
int argc = 0;
char* argv[30];
glutInit(&argc, argv); [snip] glutDisplayFunc (displayFunctio nPtr);
glutIdleFunc(di splayFunctionPt r);
glutKeyboardFun c(keyboardFunct ionPtr);
glutMainLoop();
}


If Paul's suggestion doesn't help, try making the 'call-back' functions
'static'. That worked for me in one Glut pgm I was playing with. See (google
for) 'GlutMaster' [1]

class World{
public:
static void Display();
static void Keyboard(unsign ed char key, int x, int y);
};
void World::Display( ){
glClear(GL_COLO R_BUFFER_BIT); // clear all pixels
// Do OpenGL stuff...
}
void World::Keyboard (unsigned char key, int x, int y){
cout << key << endl;
// Handle keyboard...
}

[1] - might still be at URL: http://www.duke.edu/~stetten/GlutMaster/
--
Bob R
POVrookie
Mar 18 '06 #5
Thanks for the replies.

The link to the "pointers-to-members" page should do the trick.

Also, I tried making the member functions static. This worked, but then
I couldn't access member variables.

Cheers,

Chris

Mar 18 '06 #6
I'm still having problems with this.

I've had a look at the "pointers-to-members" page. It says that
Normal C functions can be thought of as having a different calling convention from >member functions, so the types of their pointers (pointer-to-member-function vs. >pointer-to-function) are different and incompatible. C++ introduces a new type of >pointer, called a pointer-to-member, which can be invoked only by providing an object.
Does this mean that the only way I can get this to work is by passing
the object that contains the member functions? In this case, do I need
to pass function pointers at all, as I can access the functions via the
object?

As I mentioned above, I have a World object that contains a GUI object.
The GUI object requires a pointer to a member function ("Display") in
the World object. Is there a better way to do this?

Cheers,

Chris
cp******@yahoo. com wrote: Thanks for the replies.

The link to the "pointers-to-members" page should do the trick.

Also, I tried making the member functions static. This worked, but then
I couldn't access member variables.

Cheers,

Chris


Mar 18 '06 #7
<cp******@yahoo .com> wrote in message
news:11******** *************@i 39g2000cwa.goog legroups.com...
Does this mean that the only way I can get this to work is by passing
the object that contains the member functions? In this case, do I need
to pass function pointers at all, as I can access the functions via the
object?


If there is a void* parameter that is provided for you as a "user defined
data" parameter, you can use the void* as the pointer to the object, and
then retrieve it again when the function gets called.

Of course, the instance of the object must still exist.

Note that this is just one of many ways to do this. The bottom line is that
you have an object instance, and when the API executes the callback, you
retrieve that instance in some way so you can get the member data -- this is
where you have to be creative. That's what it all boils down to.

How to retrieve the instance can be accomplished in many different ways.
The simplest being making a global object (as the C++ FAQ illustrates), or
you can get fancy with maps and handles (this is usually done for OO GUI
classes), or you can use the void* option if the API's callback allows this.

- Paul
Mar 18 '06 #8

cp******@yahoo. com wrote in message ...

Also, I tried making the member functions static. This worked, but then
I couldn't access member variables.

Cheers,
Chris


I ran into that too. Make the variables 'static' so you can access them from
'Display' and 'Keyboard'. There should not be very many. A static var can be
accessed by non-static member functions.

Otherwise, you need to post a lot more of your code[1] AND the exact errors
you are getting, so the experts in this NG can figure it out.

[1] - less the OpenGL stuff that does not apply to the problem
(glClearColor() , glShadeModel(), etc.). You should separate initialize and
draw into to different functions anyway, it will make a difference when you
animate. Example below is to show you can access static vars from non-static
member functions, not how to do OpenGL (which is off-topic in this NG).

// - in class declaration, define outside -
// ---------------------------------------
static GLfloat RotAngle;
static float xspeed; // X Rotation Speed
static float yspeed; // Y Rotation Speed
static GLfloat AngleX; // Angle For Rotation (deg)
static GLfloat AngleY; // Angle For Rotation (deg)
// ---------------------------------------
// - non-static member function -
// ===== DrawGLScene ===== wxWidgets version
void BobGLCanvas::Dr awGLScene(){ // Drawing done here
wxClientDC dc( this ); // no 'this' if static
if( !GetContext() ){ return;}
SetCurrent();
glClear(GL_COLO R_BUFFER_BIT | GL_DEPTH_BUFFER _BIT);
glLoadIdentity( ); // Reset View
gluLookAt(0.0, 0.0, ZoomZ, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); //GLfloat
ZoomZ(1.50F);
glLightfv( GL_LIGHT0, GL_POSITION, lightPosition ); // Set light0
position
if( xspeed || yspeed ){
glRotatef(Angle Y*yspeed, 0.0f, 1.0f, 0.0f); // Rotate On Y axis
glRotatef(Angle X*xspeed, 1.0f, 0.0f, 0.0f); // Rotate On X axis
}
else{
glRotatef(RotAn gle, 0.0f, 1.0f, 0.0f); // Rotate on Y
axis
}
Material(MatNum ber); // Material(2) default
glCallList( listRockNum + listOffset); // Draw the Rock
SwapBuffers(); // Swap Buffers to make rendering visible
return;
} // DrawGLScene()
//---------------------------------------------
--
Bob R
POVrookie
Mar 18 '06 #9
I've implemented the "static" approach and it seems to be working.

Cheers,

Chris
BobR wrote:
cp******@yahoo. com wrote in message ...

Also, I tried making the member functions static. This worked, but then
I couldn't access member variables.

Cheers,
Chris


I ran into that too. Make the variables 'static' so you can access them from
'Display' and 'Keyboard'. There should not be very many. A static var can be
accessed by non-static member functions.

Otherwise, you need to post a lot more of your code[1] AND the exact errors
you are getting, so the experts in this NG can figure it out.

[1] - less the OpenGL stuff that does not apply to the problem
(glClearColor() , glShadeModel(), etc.). You should separate initialize and
draw into to different functions anyway, it will make a difference when you
animate. Example below is to show you can access static vars from non-static
member functions, not how to do OpenGL (which is off-topic in this NG).

// - in class declaration, define outside -
// ---------------------------------------
static GLfloat RotAngle;
static float xspeed; // X Rotation Speed
static float yspeed; // Y Rotation Speed
static GLfloat AngleX; // Angle For Rotation (deg)
static GLfloat AngleY; // Angle For Rotation (deg)
// ---------------------------------------
// - non-static member function -
// ===== DrawGLScene ===== wxWidgets version
void BobGLCanvas::Dr awGLScene(){ // Drawing done here
wxClientDC dc( this ); // no 'this' if static
if( !GetContext() ){ return;}
SetCurrent();
glClear(GL_COLO R_BUFFER_BIT | GL_DEPTH_BUFFER _BIT);
glLoadIdentity( ); // Reset View
gluLookAt(0.0, 0.0, ZoomZ, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); //GLfloat
ZoomZ(1.50F);
glLightfv( GL_LIGHT0, GL_POSITION, lightPosition ); // Set light0
position
if( xspeed || yspeed ){
glRotatef(Angle Y*yspeed, 0.0f, 1.0f, 0.0f); // Rotate On Y axis
glRotatef(Angle X*xspeed, 1.0f, 0.0f, 0.0f); // Rotate On X axis
}
else{
glRotatef(RotAn gle, 0.0f, 1.0f, 0.0f); // Rotate on Y
axis
}
Material(MatNum ber); // Material(2) default
glCallList( listRockNum + listOffset); // Draw the Rock
SwapBuffers(); // Swap Buffers to make rendering visible
return;
} // DrawGLScene()
//---------------------------------------------
--
Bob R
POVrookie


Mar 18 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
9377
by: Newsgroup - Ann | last post by:
Gurus, I have the following implementation of a member function: class A { // ... virtual double func(double v); void caller(int i, int j, double (* callee)(double)); void foo() {caller(1, 2, func);
58
10181
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
12
2092
by: Anthony Jones | last post by:
Just a bit of background: I'm one of a group of FORTRAN programmers, looking to switch to C++. We are trying to write a few simple examples to demonstrate the power of the language to our manager, so he will send us all on a conversion course. One of many reasons is that our code is littered with examples of: SUBROUTINE PRINT_ITEM(ITEM, ITEM_TYPE) IF (ITEM_TYPE .EQ. SQUARE) THEN CALL PRINT_SQUARE(ITEM)
2
3640
by: joe | last post by:
hi, after reading some articles and faq, i want to clarify myself what's correct(conform to standard) and what's not? or what should be correct but it isn't simply because compilers don't support. (first i compiled them with g++3.x. ERR means compiler will bark, otherwise it does accept it. Then the Comeau C/C++ 4.3.3 comes)
7
2497
by: Steven T. Hatton | last post by:
I am trying to convert some basic OpenGL code to an OO form. This is the C version of the program: http://www.opengl.org/resources/code/basics/redbook/double.c You can see what my current effort at converting that code to an OO form looks like in the code listed below. The problem I'm running into is that the OpenGL functions that take the names of other functions as arguments don't like the way I'm passing the member functions of my...
6
8830
by: keepyourstupidspam | last post by:
Hi, I want to pass a function pointer that is a class member. This is the fn I want to pass the function pointer into: int Scheduler::Add(const unsigned long timeout, void* pFunction, void* pParam)
3
2622
by: dice | last post by:
Hi, In order to use an external api call that requires a function pointer I am currently creating static wrappers to call my objects functions. I want to re-jig this so I only need 1 static wrapper function. I would prefer to be able to pass the member function as a void* to the static wrapper but I suspect this may not even be possible. Another solution would be option 2 below but I can't figure out the syntax to call obj->*pFn(). ...
18
2879
by: tbringley | last post by:
I am a c++ newbie, so please excuse the ignorance of this question. I am interested in a way of having a class call a general member function of another class. Specifically, I am trying to write an ordinary differential equation class that would solve a general equation in the form: dx/dt = f(x,t). The ode class shouldn't know anything about f, except how to call it.
23
2153
by: osama178 | last post by:
Let's say I have this code -------------------- class GenericQueue { public: bool Pop(void*& refToPtr); // //--------------------(1) };
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.