Macro works in C++ , but not in C, why?

Started by bitcoin, October 30, 2020, 01:12:39 PM

Previous topic - Next topic

bitcoin

Hello
this macro works in Cpp, but in C given an error. Why?

#define MakePtr(Type, Base, Offset) ((Type)(DWORD(Base) + (DWORD)(Offset)))

usage
PIMAGE_EXPORT_DIRECTORY pImportDesc=NULL;
pImportDesc = MakePtr(PIMAGE_EXPORT_DIRECTORY,PE,pNtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);

algernon_77

I'm not sure I understand, you're saying that it compiles under C++ but not on C? Or that it compiles, but it crashes when running the binary generated with C compiler?

First of all, it should be

#define MakePtr(Type, Base, Offset) ((Type)((DWORD)(Base) + (DWORD)(Offset)))


Note the extra paranthesis around the first DWORD

Second, the macro works correctly on 32 bit only; in 64 bit, it will truncate the pointers, so we'll change it to

#define MakePtr(Type, Base, Offset) ((Type)((DWORD_PTR)(Base) + (DWORD_PTR)(Offset)))


DWORD_PTR type is in fact ULONG_PTR, which translates to unsigned int64 when compiled for 64bit and unsigned int32 when compiled for x86.

bitcoin