Innovare
Innovare

Reputation: 23

C++ function pointers and callback functions

I'm not a C++ guy and I'm having some trouble understanding how to pass a function pointer/callback function to a method. The callback is defined as follows

typedef HRESULT (CALLBACK *PFN_CREATE_XAMLOBJECT)(
    IXRDependencyObject *pExistingXRDO,
    UINT objectId
);

The method I am attempting to pass it too is defined as follows (all other params removed)

virtual HRESULT STDMETHODCALLTYPE RegisterXamlObject(
    __in    PFN_CREATE_XAMLOBJECT   pfXamlObjectCreation,
) = 0;

The function I have defined to pass on is as follows

HRESULT CreateFn(__in IXRDependencyObject *pExistingXRDO, UINT objectId)
{
    return S_OK;
}

I am attempting to pass the the function pointer as follows.

&MyClass::CreateFn

I get the following error

Error   3   error C2440: 'type cast' : cannot convert from 'HRESULT (__cdecl MyClass::* )(IXRDependencyObject *,UINT)' to 'PFN_CREATE_XAMLOBJECT'

Any help would be much appreciated.

Upvotes: 2

Views: 1559

Answers (3)

Cory Nelson
Cory Nelson

Reputation: 30021

Two problems here.

First, a function pointer can not point to a member function, because a member function requires a this pointer to operate. You must make the member function static, or make the pointer a member function pointer.

Second, the function pointer and the function must use the same calling convention. The pointer uses CALLBACK, which is defined to __stdcall.

Here's a revised function:

static HRESULT CALLBACK CreateFn(IXRDependencyObject *pExistingXRDO,
                                 UINT objectId)
{
    return S_OK;
}

Upvotes: 2

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

A member function needs an object to be called on which you're not passing, while what you want is a normal function.

Use a static method in your class instead, that does not require an object pointer to be passed to it.

Upvotes: 0

Lorenzo Pistone
Lorenzo Pistone

Reputation: 5188

you must pass a plain function, not a member function (a function which is a field of a class). They are distinct objects, in fact, the method takes a hidden additional argument, which is obviously the pointer to this (the object the method is called on). If you want to enclose the callback definition in a class anyway, make it a static method.

Upvotes: 0

Related Questions