Pointers to functions

Posted on 2002-06-10
Last Modified: 2008-01-16
Hi, I have created an RS232 class, but I want to change where the results are delivered to on the fly.

in the public: I have declared

        void MyFunction(BYTE *,int );
        void (*pDeliverData)(BYTE *,int );

Then on implementation
pDeliverData = MyFunction;//I get an error:
[C++ Error] rs232Thread.cpp(38): E2235 Member function must be called or its address taken.

So I then tried
pDeliverData = &MyFunction;//I then get the error:
[C++ Error] rs232Thread.cpp(38): E2034 Cannot convert 'void (* (_closure )(unsigned char *,int))(unsigned char *,int)' to 'void (*)(unsigned char *,int)'.

Ideally I want the thread that created the object to be able to assign a new return function.

Ant tips would be great, thanks.
Question by:dsch
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 86

Expert Comment

ID: 7067726
Pointers to member functions are significantly different from function pointers - they do not work without an instance of the class. In your sample, it should be

void (MyClass::*pDeliverData)(BYTE *,int );

Expert Comment

ID: 7067742
So MyFunction is member of the class?
If so the reason it fails is that signature of member class is different.

if you have

class A{
  void f(BYTE*,int);

in reality f have a signature of void f(A*,BYTE*,int).  See, the first argument of a member function is ALWAYS pointer to class it belongs to.  
You can try solve this problem by trying to declaring MyFunction static.

Hope it helps..
LVL 22

Expert Comment

ID: 7067829
>> See, the first argument of a member function
>> is ALWAYS pointer to class it belongs to.  
That is not true.   The procedure for passing the "this pointer" is impliementaion defined.   It often is not passed in the same way as the other parameters.

dsch, what jkr and mblat hare saying is that a non-static member function is inheriently different than a free function (a non-member function or a static member function).   The non-staitc member function takes a hidden parameter that the free function does not.  The parameter is a pointer to the object for which the function is invoked.  In other wirds, the "this" pointer is passed to the function as a hidden parameter.  Free functions don't have this parameter, and thus can never be "equivalent" to a non-static member function.    

For this reason, a pointer to a non-static member function can never be equivalent to, or convertable to, a pointer to a free function and vice versa.

Pointers to member functions have a unique syntax that is similar to, but different from pointers to free functions.

here is a short example of how pointers-to-members are declared and used

class Cls
   int Add(int i1,int i2) { return i1 + i2 };
   int Sub(int i1,int i2) { return i1 - i2 };
   int Abs(int i) { return i <0? -1*i:i; };

// member function pointer typedef.  Not
// necessary, except for readability.
typedef int (Cls::*MbrFunPtrTyp)(int,int);
// This type is a pointer to a member function of Cls that
// takes 2 ints as parameters and returns a int.  
// Thus this type of pointer can point to Add() or Sub()
// but not to Abs().

// Declare and use a pointer of this type.
MbrFunPtrTyp FunPtr = &Cls::Add; // make pointer to add function.
Cls C;                             // Declare object of the class
Cls *CPtr = &C;            // Declare pointer to object of the class.

int R1 = (C.*FunPtr)(1,2); // Add 1 and 2 using a Cls object.
int R2 = (CPtr->*FunPtr)(1,2); // Add 1 and 2 using a pointer to a Cls object.

FunPtr = &Cls::Sub; // Make pointer to Sub function.

int R3 = (C.*FunPtr)(1,2); // Subtract1 and 2 using a Cls object.
int R4 = (CPtr->*FunPtr)(1,2); // Subtract 1 and 2 using a pointer to a Cls object.

Note that the functions that the pointer-to-member pointer will be used with must have the same signature.  To be precise they must:

1. be members of the same class.
2. have the same parameters.
3. have the same return value
4. Have the same calling convention.  

Thus the example above the function pointer could be used with Add() and Sub(), but not with Abs().  You could define a seperate function pointer type that could be used with Abs() and other member functions of Cls that have the same parameters and signature etc.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 7068242
Hmmm, Thanks for this info, & I understand how to point to a member function, but what I am actually attempting to do, is pass INTO the Class pointer function.
Sorry this is hard to explain:
I have a Form which on activate creates an object (RS232 comms). The RS232 Object creates a new thread to monitor and deliver the incomming data.
I currently have it directly accessing the forms function:
Form1->DealWithData(S,BufferSize); //S is a char*, BufferSize is the length og buffer. Yawn!

However this does not make it very portable, and I alos want to request data of different sizes and process it with a different function. So Ideally, I want to have the pointer  to the function IN the class, so that when I call it (from within the class)(with the same parameters obviously) it delevers the data to the appropriate function.
ie the member function calls a function external to the class.

Does that explain it? I hope so.

Thanks again
LVL 22

Expert Comment

ID: 7068307
>> the member function calls a function external to the class.
That sounds like you are calling an ordinary free function.  That is easy.  I'm not sure what your problem is.  We really need to see more of your code.

An example would be

// For convenience, declare a typedef for the pointer type.
typedef void (*FunctionPtrType)(BYTE *,int);

class X
    FunctionPtrType  Ptr; // The pointer to your function.
   SetPtr(FunctionPtrType P)
     Ptr = p;
   void Execute()  
      Ptr(SomePtr,5); // Make the call here.

Author Comment

ID: 7068415
More Code.. Here goes:
#ifndef rs232ThreadH
#define rs232ThreadH
#include <Classes.hpp>
class RS232RXThread : public TThread
        HANDLE hCom;
        DWORD dwError,eMask;
        AnsiString *Str1;
        void ShowLastError();
        int FBufferSize;
        int GetBufferSize()const;
        void SetBufferSize(int);
        void __fastcall Execute();
        void (*pDeliverData)(BYTE *,int );
        __fastcall RS232RXThread(bool CreateSuspended,HANDLE hCom1);
        __property int BufferSize = {read = GetBufferSize, write = SetBufferSize};


#include <vcl.h>
#pragma hdrstop

#include "rs232Thread.h"
#include "Comms1.h"
#pragma package(smart_init)
__fastcall RS232RXThread::RS232RXThread(bool CreateSuspended, HANDLE hCom1)
        : TThread(CreateSuspended),FBufferSize(0)
        hCom = hCom1;
        Str1 = new AnsiString();
void __fastcall RS232RXThread::Execute()
DWORD ByteCount;
char S[100];
bool Waiting = FALSE;
// Create the overlapped event. Must be closed before exiting
// to avoid a handle leak.
DWORD dwCommEvent=0;
DWORD dwCommMask = 0;
//pDeliverData = &MyFunction;

dwCommMask =  EV_RXCHAR;
SetCommMask(hCom, dwCommMask);

  DWORD lpErrors;
  COMSTAT lpStat;
  ByteCount = 1;
  osReader.hEvent = CreateEvent(
    NULL,   // no security attributes
    FALSE,  // auto reset event
    FALSE,  // not signaled
    NULL    // no name

for(;;) {
   if (!WaitCommEvent(hCom, &dwCommEvent, &osReader))

     if (GetLastError() == ERROR_IO_PENDING)
//overlapped I/O-operation cannot be completed immediately operation in background)
         Waiting = TRUE;

                  hCom,     // handle to communications device
                  &lpErrors, // error codes
                  &lpStat  // communications status

if (lpStat.cbInQue >= BufferSize)//dwCommEvent & EV_RXCHAR)

        if(ReadFile(hCom, &S, BufferSize/*lpStat.cbInQue*/, &ByteCount, &osReader))
                   // A byte has been read; process it.
                S[ByteCount] = 0;
                Form1->DealWithData(S,BufferSize);  //Routine in calling thread
                  // To do.
                Waiting = FALSE;
                dwCommEvent = 0;
}// end else

}//end While
}//end of function

void RS232RXThread::ShowLastError()
LPVOID lpMsgBuf;
                  FORMAT_MESSAGE_FROM_SYSTEM |
                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                  (LPTSTR) &lpMsgBuf,
               // Display the string.
               MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
               // Free the buffer.
               LocalFree( lpMsgBuf );

int RS232RXThread::GetBufferSize()const
return FBufferSize;

void RS232RXThread::SetBufferSize(int Buf)
FBufferSize = Buf;

Form1->DealWithData(S,BufferSize); is the routine outside that I want to call, but via  pointer to the function.
Form1 is a TForm object in  Borland VCL.
I want to pass in different functions but with the same parameters to receive the data.

LVL 22

Accepted Solution

nietod earned 50 total points
ID: 7068430
Well you posted the line that causes the problem.

>> pDeliverData = &MyFunction;

but without posting MyFunction, we can't see what the problem is.

Note that MyFunction must be a free function (a static class member or a non-member.)

Note that it must have the right parameter, like

void MyFunction(BYTE *ptr,int i)

We need to see this definition/declaration.  It must not be in a class.  Or if it is in a class, it must be static, like

static void MyFunction(BYTE *ptr, int i)
LVL 30

Expert Comment

ID: 7068463
If it is in a class, there are methods to get it to work as a non-static member, but it's not a straight forward method.

Please post the function and your requirements.

Author Comment

ID: 7068478
Forget MyFunction, this was remmed out a few hours ago.

I have just declared the member function as statis and it works now when calling the function pointer in the RS232Thread class.

I will now accept this as an answer.
Thanyou very much
David (and thanks jkr & mblat)

Author Comment

ID: 7068479
Great, I understand this so much more now.
Kind Regards

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
getting a fire fox page (view page source ) in c++ 6 47
Socket Programming (Unix) 8 158
How to convert MFC APP to Win32 APP. 19 131
Safe conversion? 4 84
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question