Reputation: 65
could anybody explain me how to read DWORD ,WORD ,BYTE in C from specific address in memory?
for example, base address that is returned using MapViewOfFile() function,how can I read a consecutive BYTE,WORD, or DWORD using C ?
Thanks.
Upvotes: 0
Views: 3681
Reputation: 90422
Well your question has basically two parts:
could anybody explain me how to read DWORD
,WORD
,BYTE
in C from specific address in memory?
That's easy, but probably not what you want, you simply cast the address to a pointer of the desired type.
DWORD x = *((DWORD *)address);
for example, base address that is returned using MapViewOfFile()
function,how can I read a consecutive BYTE
,WORD
, or DWORD
using C ?
That's also not too bad. You are getting a void*
from MapViewOfFile
, simply cast it or assign it to an appropriate pointer type and then you can use it like an array:
DWORD *p = MapViewOfFile(...);
DWORD x = p[1]; // second DWORD of the mapped file
Upvotes: 1
Reputation: 380
MapViewOfFile()
returns LPVOID
which is a typedef of void*
. You'll need a cast.
The easiest thing to do would be to read a byte at a time. You don't specify if there's any kind of performance requirement here (nor do you specify your platform, arch, etc), so I'll assume a "byte at a time" is ok.
Note: WORD is defined as short and should be 16-bits in Win32. DWORD is an int and should be 32-bits in Win32.
LPVOID pvAddr= MapViewOfFile(...);
BYTE* pBytes= (BYTE*)pvAddr;
BYTE firstByte= pBytes[0]; /* copy first byte */
WORD w;
memcpy(&w, pBytes+1, 2); /* copy the next two bytes */
DWORD dw;
memcpy(&dw, pBytes+3, 4); /* copy the next 4 bytes */
Hope that helps.
Upvotes: 1
Reputation: 129314
Assuming that the address is aligned suitably for the datatype you are using - this is important as in some architectures, it's invalid to access an "unaligned" address!
In C:
void *address = MapViewOfFile(...);
DWORD *dword_ptr = (DWORD *)address;
WORD *word_ptr = (WORD *)address;
BYTE *byte_ptr = (BYTE *)address;
In C++, the pattern is similar, but instead of a basic C style cast, you should use reinterpret_cast<type*>(address)
, where type
is DWORD
, WORD
, BYTE
, etc. E.g.:
DWORD *dword_ptr = reinterpret_cast<DWORD *>(address);
Upvotes: 1
Reputation: 8053
MapViewOfFile
returns an LPVOID
(which is equivalent to a void *
) so it can be read like any other pointer.
Upvotes: 0