简体   繁体   中英

How can I get the address of a COM object's member function?

I have a pointer to a COM object pfoo implements IFoo. I'd like to get the address of pfoo->Bar(), one of the methods of IFoo. Since COM objects are quite well documented, this should be pretty easy. And in fact, it is. If Bar() is, say, the fifth method in the interface (accounting of course for the IUnknown methods), the address can be extracted from the vtable with

(*(void***)(pfoo))[5]

My question is, is there a way to do this without having to use "5"? It seems error-prone to have to count up the methods. I want to use only the method name. I don't mind if it's a bit complex; this is all going in a macro anyway. So my ultimate question is, does there exist a macro that takes the parameters pfoo, Bar, and maybe IFoo, and evaluates to the expression above?

No, there is not a macro to do that. It's your funeral if you want to do that.

Just don't forget that if your interface is derived from IUnknown, then the 5th function is not the 5th function in the interface, but the 8th because before the first method in the interface there is QueryInterface, AddRef, and Release--not necessarily in that order. If you are derived from IDispatch, there is even more methods before your first method.

If you look at MFC source code, they use some macros to do some similar things in their METHOD_PROLOGUE() macro. It uses either a macro or MS compiler hack titled "offsetof()". I don't know which it is and am not inclined to look it up, but since MS provides the source code, you should be able to do it.

Edit: I just googled it and it appears that offsetof() is a stddef.h macro. https://en.wikipedia.org/wiki/Offsetof

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM