What is "BYTE" and "PBYTE" used for?.I couldn't find any information on the internet.
#include <iostream>
#include <Windows.h>
using namespace std;
BYTE by='a';
PBYTE pby= &by;
int main(){
cout<<"by : "<<by<<endl;
cout<<"&by : "<<&by<<endl; // Why doesn't it return the memory address?
cout<<"pby : "<<pby<<endl;
cout<<"&pby: "<<&pby;
return 0;
}
The console shows:
by : a
&by : a
pby : a
&pby: 00007FF6CC10A008
I just want to know what BYTE and PBYTE are used for. I can not understand. Thanks
CodePudding user response:
BYTE,PBYTE is very old style in windows programming. If you want to allocate heap memory for your image loader for example, you can write
unsigned char* img = new unsigned char[1024 * 1024];
load_image(img, ....);
conv_image(img, ....);
But your finger would be tired, so you can write
PBYTE img = new BYTE[1024 * 1024];
Yes, microsoft invented these defined types over 20yr ago. But it is not portable and not follows standards and cause memory leaks, so in the 21st century, you should write as described below.
auto img = make_shared<uint8_t>(1024 * 1024);
or
vector<uint8_t> v(1024 * 1024);
or
array<uint8_t, 1024 * 1024> a; // need enough stack memory
CodePudding user response:
What is "BYTE" and "PBYTE" used for?
BYTE
is a type alias for unsigned char
and PBYTE
is a type alias for BYTE *
, a.k.a. unsigned char *
. They are used in the WINAPI as same their "real" type - unsigned char
and a pointer to a unsigned char
In your code:
cout << "&by : ";
cout << "&phy : ";
will take the pointer of that string literal in memory, and print out all the the characters that follows until it reached a \0
(that how null-terminated string works). Then, it returns a basic_ostream<char, _Traits>&
, allowing you to chain multiple calls.
When you call cout << &by
, you are calling the overloaded operator for basic_ostream << const unsigned char *__s
. If you dig a little deeper in the code,
template<typename _Traits> inline basic_ostream<char, _Traits>&
operator<<(basic_ostream<char, _Traits>& ___out, const unsigned char* __s)
{
return (___out << reinterpret_cast<const char*>(__s));
}
You will find that what is does is simply casting that const unsigned char*
to a const char*
(Notice how the unsigned char*
is a const
because it is a global variable). In another word, it works exactly same as cout << reinterpret_cast<const char*>(&by)
, where the program treat your &by
as a null-terminated string. Since the allocated on the stack is reset to \0
s, the by
is same as a one-character long null-terminated string ("a\0"
).
On the another hand, when you call cout << &pby
, you are calling the overloaded operator for __ostream_type& << const void*
. The program is casting the PBYTE *
to a void pointer as there isn't an overload for PBYTE *
(BYTE **
). In this case, it simply print out the address of pby
.
__ostream_type& operator<<(const void* __p) {
return _M_insert(__p);
}