Pelles C forum

C language => Beginner questions => Topic started by: bitcoin on October 30, 2020, 01:12:39 PM

Title: Macro works in C++ , but not in C, why?
Post by: bitcoin on October 30, 2020, 01:12:39 PM
Hello
this macro works in Cpp, but in C given an error. Why?

Code: [Select]
#define MakePtr(Type, Base, Offset) ((Type)(DWORD(Base) + (DWORD)(Offset)))
usage
Code: [Select]
PIMAGE_EXPORT_DIRECTORY pImportDesc=NULL;
pImportDesc = MakePtr(PIMAGE_EXPORT_DIRECTORY,PE,pNtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
Title: Re: Macro works in C++ , but not in C, why?
Post by: algernon_77 on October 30, 2020, 05:39:43 PM
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
Code: [Select]
#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
Code: [Select]
#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.
Title: Re: Macro works in C++ , but not in C, why?
Post by: bitcoin on November 02, 2020, 12:42:10 AM
Thank you, your macros works!