NO

Author Topic: Macro works in C++ , but not in C, why?  (Read 2645 times)

Offline bitcoin

  • Member
  • *
  • Posts: 179
Macro works in C++ , but not in C, why?
« 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);

Offline algernon_77

  • Member
  • *
  • Posts: 33
Re: Macro works in C++ , but not in C, why?
« Reply #1 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.

Offline bitcoin

  • Member
  • *
  • Posts: 179
Re: Macro works in C++ , but not in C, why?
« Reply #2 on: November 02, 2020, 12:42:10 AM »
Thank you, your macros works!