2

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.

1
  • have you defined CreateFn as static? Commented Jan 19, 2012 at 17:09

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answers folks. Super fast!
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.