Tchar c что это
Перейти к содержимому

Tchar c что это

LPSTR, LPWSTR, TCHAR, char*, .

TCHAR — это изобретение Microsoft и куча проблем с ним связано. Если у вас проект на Unicode, то это TCHAR = wchar_t. Если ASCII то TCHAR = char.

Поскольку TCHAR в исходниках примеров драйверов повсюду надо понимать как с ним далее работать. Как следствие надо использовать Windows Safe String Function для разных преобразований:

Присвоить значение TCHAR строке :

Если надо int в TCHAR преобразовать (int -> TCHAR):

Присваивание значений строкам

LPCSTR понимается так.
• LP — Long Pointer (длинный указатель)
• C – Constant (константа)
• STR – String (строка)
По сути LPCSTR это (Длинный) указатель на строку.

LPSTR общеприменяемый префикс с названии sz

LPCWSTR,LPWSTR описан так:

LPCTSTR
LP — Long Pointer (Длинный указатель)
C — Constant (Константа)
T = TCHAR
STR = String (Строка)

Что такое STRSAFE? Смотрим strsafe.h :

Там же в strsafe.h :

Скопировать TCHAR* в char* (универсальный вариант)

wcstombs(ipAddres, ourIpAdress, sizeof(ourIpAdress)); к сожалению только если UniCode исползуется

Что такое TCHAR, WCHAR, LPSTR, LPWSTR,LPCTSTR (итд)

Многие C++ программисты, пишущие под Windows часто путаются над этими странными идентификаторами как TCHAR, LPCTSTR. В этой статье я попытаюсь наилучшим способом расставить все точки над И. И рассеять туман сомнений.

В свое время я потратил много времени копаясь в исходниках и не понимал что значат эти загадочные TCHAR, WCHAR, LPSTR, LPWSTR,LPCTSTR.
Недавно нашел очень грамотную статью и представляю ее качественный перевод.
Статья рекомендуется тем кто бессонными ночами копошиться в кодах С++.

Вам интересно ??
Прошу под кат.

В общем, символ строки может быть представлен в виде 1-го байта и 2-х байтов.
Обычно одно-байтовый символ это символ кодировки ANSI- в этой кодировке представлены все английские символы. А 2-х байтовый символ это кодировка UNICODE, в которой могут быть представлены все остальные языки в мире.

Компилятор Visual C++ поддерживает char и wchar_t как встроенные типы данных для кодировок ANSI и UNICODE.Хотя есть более конкретное определение Юникода, но для понимания, ОС Windows использует именно 2-х байтовую кодировку для много языковой поддержки приложений.

Что делать если вы хотите чтобы ваш С/С++ код был независимым от кодировок и использование разных режимов кодирования?

СОВЕТ. Используйте общие типы данных и имена для представления символов и строк.

Например, вместо того чтобы менять следующий код:

В целях поддержки многоязычных приложений (например, Unicode), вы можете писать код в более общей манере.

В настройках проекта на вкладке GENERAL есть параметр CHARACTER SET который указывает в какой кодировке будет компилироваться программа:

Если указан параметр «Use Unicode Character set», тип TCHAR будет транслироваться в тип wchar_t. Если указан параметр «Use Multi-byte character set» то тогда TCHAR будет транслироваться в тип char. Вы можете свободно использовать типы char и wchar_t, и настройки проекта никоим образом не повлияют на использование этих ключевых слов.

TCHAR определен так:

Макрос _UNICODE будет включен если вы укажите «Use Unicode Character set» и тогда тип TCHAR будет определен как wchar_t. Когда же вы укажите «Use Multi-byte character set» TCHAR будет определен как char.

Помимо этого, для того что была поддержка нескольких наборов символов используя общий базовый код, и возможно поддержки много языковых приложений, используйте Специфические функции (то есть макросы).
Вместо того чтобы использовать strcpy, strlen, strcat (в том числе защищенные варианты функции с префиксом _s), или wcscpy, wcslen, wcscat (включая защищенные варианты), вам лучше использовать функции _tcscpy, _tcslen, _tcscat.

Как вы знаете функция strlen описана так:

И функция wcslen описана так:

Вам лучше использовать _tcslen, который логически описан так:

WC это Wide Character (Большой символ). Поэтому, wcs функции будут для wide-character-string (то есть для большой-символьной-строки).Таким образом _tcs будет означать _T символьная строка. И как вы знаете строки с префиксом _T могут быть типа char или wchar_t.

Но в реальности _tcslen (и другие функции с префиксом _tcs) вовсе не функции, это макросы. Они просто описаны как:

Вы можете просмотреть заголовочный файл TCHAR.H и поискать там еще Макро описания похожее на вышеупомянутое.

Таким образом TCHAR оказывается вовсе не типом, а надстройкой над типами char и wchar_t. Позволяя тем самым выбирать мульти язычное приложение у нас будет или же все таки, одно язычное.

Вы спросите почему они описаны как макросы, а не как полноценная функция ??
Причина проста: Библиотека или DLL могут экспортировать простую функцию с тем же именем и прототипом (Исключая концепцию перегрузки в С++).
Для примера если вы экспортируете функцию:

Как должен вызывать ее клиент ?? Как:

_TPrintChar магическим образом может быть преобразована в функцию принимающая двух байтовый символ в качестве аргумента.

Для этого мы сделаем две различные функции:

И простой макрос скроет разницу между ними:

Клиент просто вызовет функцию как

Заметьте, что TCHAR и _TPrintChar теперь будут сопоставимы с UNICODE или ANSI, а переменная cChar и параметр функции будет сопоставим с типом данных char или wchar_t.

Макросы дают нам обойти эти сложности, и позволяют нам использовать ANSI или UNICODE функции для наших символов и строк. Множество функций Windows описаны именно таким образом, и для программиста есть только одна функция (то есть макрос) и это хорошо.

Приведу пример с SetWindowText:

Есть только несколько функций у которых нету таких макросов, и они только с суффиксом W или A. Пример тому функция ReadDirectoryChangesW, которая не имеет эквивалента в кодировки ANSI.

Как вы знаете, мы используем двойные кавычки для представления строк. Строка представленная в этой манере это ANSI-строка, на каждый символ используется 1 байт. Приведу пример:

Указанная верху строка не является строкой UNICODE, и не подходит для много языковой поддержки. Для того чтобы получить UNICODE строку вам надо использовать префикс L.
Приведу пример:

Поставьте спереди L и вы получите UNICODE строку. Все символы (Я повторяю все символы ) занимают 2 байта, включая Английские буквы, пробелы, цифры и символ null. Объем данных строки Unicode всегда будет кратен 2-м байтам. Строка Unicode длиной 7 символов будет занимать 14 байтов. Если строка Unicode занимает 15 байтов то это не правильная строка, и она не будет работать в любом контексте.

Также, строка будет кратна размеру sizeof(TCHAR) в байтах.

Когда Вам нужно жестко прописанный код, вы можете писать код так:

Строки без префикса это ANSI строки, с префиксом L строки Unicode, и строки с префиксом _T и TEXT зависимые от компиляции. И опять же _T и TEXT это снова макросы. Они определены так:

Символ ## это ключ(token) вставки оператора, который превратит _T(«Unicode») в L«Unicode», где строка это аргумент для макроса- если конечно _UNICODE определен.
Если _UNICODE не определен то _T(«Unicode») превратит это в «Unicode». Ключ вставки оператора существовал даже в языке С, и это не специфическая вещь связанная с кодировкой строк в VC++.

К сведению, макросы могут применятся не только для строк но и для символов. Например _T(‘R’) превратит это в L’R’ ну или в просто ‘R’. Тоесть либо в Unicode символ либо в ANSI символ.

Нет и еще раз нет, вы не можете использовать макрос чтобы конвертировать символ или строку в Unicode и не Unicode текст.
Следующий код будет неправильным:

Строки _T( c); _T(str); отлично скомпилируются в режиме ANSI, _T(x) превратится в x, и _T( c) вместе с _T(str) превратятся просто в c и str.
Но когда вы будете собирать проект в режиме Unicode код не с компилируется:

Я не хотел бы вызывать инсульт вашего интеллекта и объяснять почему это не работает.

Существует несколько функций для конвертирования Мульбайтовых строк в UNICODE, о которых я скоро расскажу.

Есть важное замечание, почти все функции которые принимает строку или символ, приоритетно в Windows API, имеют обобщенное название в MSDN и в других местах.
Функция SetWindowTextA/W будет классифицирована как:

Но как Вы знаете, SetWindowText это просто макрос, и в зависимости от настроек проекта будет рассматриваться как:

Так что не ломайте голову если не сможете получить адрес этой функции:

В библиотеке User32.DLL, имеются 2 функции SetWindowTextA и SetWindowTextW которые экспортируются, то есть тут нет имен с обобщенным названием.

Все функции которые имеют ANSI и UNICODE версию, вообще то имеют только UNICODE реализацию. Это значит, что когда Вы вызываете SetWindowTextA из своего кода, передавая параметр ANSI строку — она конвертирует ANSI в UNICODE вызывает SetWindowTextW.
Реальную работу (установку заголовка/названия/метки окна) делает только Unicode версия!

Возьмем другой пример, который будет получать текст окна, используя GetWindowText.
Вы вызываете GetWindowTextA передавая ему ANSI буфер как целевой буфер.
GetWindowTextA сначала вызовет GetWindowTextW, возможно выделяя память для Unicode строки (т.е массив wchar_t).
Затем он с конвертирует Unicode в ANSI строку для вас.

  • CreateProcess
  • GetUserName
  • OpenDesktop
  • DeleteFile
  • итд

Поэтому очень рекомендуется вызывать напрямую Unicode функции.
В свою очередь, это означает, что вы всегда должны быть нацелены на сборку Unicode версии, а не на сборку ANSI версии, учитывая тот факт, что вы привыкли использовать ANSI строки в течение многих лет.

Да вы можете сохранять и получать ANSI строки, например для записи в файл, или отправки сообщения чата в ваше программе-чата. Функции конвертации существуют для таких нужд.

Замечание: Есть еще одно описание типа: имя ему WCHAR – оно эквивалентно wchar_t.

TCHAR это макрос, для декларирования одного символа. Вы также можете декларировать массив TCHAR. А что если Вы например захотите описать указатель на символы или, константный указатель на символы.
Приведу пример:

После чтения фишек с TCHAR, вы наверное предпочтете использовать именно его. Существуют еще хорошие альтернативы для представления строк в вашем коде. Для этого надо просто включить Windows.h в проект.
Примечание: Если ваш проект включает windows.h (косвенным или прямым образом), вы не должны включать в проект TCHAR.H.
Для начала пересмотрим старую функцию, чтобы было легче понять. Пример функцию strlen.

Которая может быть представлена по другому.

Где LPCSTR описан как:

LPCSTR понимается так.
• LP — Long Pointer (длинный указатель)
• C – Constant (константа)
• STR – String (строка)
По сути LPCSTR это (Длинный) указатель на строку.

Давайте изменим strcpy в соответствие с новым стилем имени типов:

szTarget имеет тип LPSTR, без использования типов языка С. LPSTR определен так:

Заметьте что szSource имеет тип LPCSTR, так как функция strcpy не модифицирует исходный буфер, поэтому выставлен атрибут const. Возвращаемый тип данных не константная строка: LPSTR.

Итак, функции с префиксом str для манипуляции с ANSI строками. Но нам нужна еще для двух байтовых Unicode строк. Для тех же больших символов имеются эквивалентные функции.
Для примера, чтобы посчитать длину символов больших символов(Unicode строки), вы будете использовать wcslen:

Прототип функции wcslen такой:

И код выше может быть представлен по другому:

Где LPCWSTR описан так:

LPCWSTR можно понять так:
LP — Long Pointer (Длинный указатель)
C — Constant (константа)
WSTR — Wide character String (строка больших символов)

Аналогичным образом, strcpy эквивалент wcscpy, для Unicode строк:

Который может быть представлен как:

Где szTarget это не константная большая строка (LPWSTR), а szSource константная большая строка.

Существует ряд эквивалентных wcs-функций для str-функций. str-функции будут использоваться для простых ANSI строк, а wcs-функции для Unicode строк.

Хотя Я уже советовал что надо использовать native Unicode функции, а не только ANSI или только синтезированные TCHAR функции. Причина проста — ваше приложение должно быть только Unicode-ным, и вы не должны заботится о том что спортируются ли они для ANSI. Но для полноты картины я и упомянул эти общие отображения (проецирования).

Чтобы вычислить длину строки, вы можете использовать _tcslen функцию (макро).
Который описан так:

Где имя типа LPCTSTR можно понять так
LP — Long Pointer (Длинный указатель)
C — Constant (Константа)
T = TCHAR
STR = String (Строка)

В зависимости от настроек проекта, LPCTSTR будет проецироваться в LPCSTR (ANSI) или в LPCWSTR (Unicode).

Заметьте: функции strlen, wcslen или _tcslen будут возвращать количество символов в строке, а не количество байтов.

Обобщенная операция копирования строки _tcscpy описана так:

Или в еще более обобщенной манере, как:

Вы можете догадаться что значит LPTSTR ))

Примеры использования.

Во первых приведу пример нерабочего кода:

На ANSI сборке, этот код успешно с компилируется потому что TCHAR будет типом char, и переменная name будет массивом char. Вызов strlen для name тоже будет прекрасно работать.

Итак. Давайте с компилируем тоже самое с включенными UNICODE/_UNICODE (в настройках проекта выберите «Use Unicode Character Set»).
Теперь компилятор будет выдавать такого рода ошибки:

И программисты начнут исправлять ошибку таким образом:

И это не усмирит компилятор, потому что конвертирование из TCHAR* в TCHAR[7] невозможно. Такая же ошибка будет возникать когда встроенные ANSI строки передаются Unicode функции:

К сожалению (или к счастью), эта ошибка может быть неправильно исправлена простым приведением типов языка C.

И вы думаете что повысили уровень своего опыта при работе с указателями. ВЫ не правы -этот код будет давать неправильный результат, и в большинстве вы будете получать Access Violation (нарушение доступа). Приведение типов таким образом это как передача float-переменной когда ожидалось(логически) структура размером 80 байт.

Строка «Saturn» это последовательность 7 байт:

‘S’ (83) ‘a’ (97) ‘t’ (116) ‘u’ (117) ‘r’ (114) ‘n’ (110) ‘\0’ (0)

Но когда вы передаете тот же набор байтов в wcslen, он рассматривает каждые 2 байта как один символ. Поэтому первые 2 байта [97,83] будут рассматриваться как один символ имеющий значение 24915(97<<8 | 83). Это Unicode символ . И другие следующие символы рассматриваются как [117,116] и так далее.

Конечно вы не передавали эти Китайские символы, но приведение типов сделало это за Вас.
И поэтому очень важно знать что приведение типов не будет работать. Итак для инициализации первой строки вы должны сделать следующее:

Который будет транслировать в 7 или в 14 байт, в зависимости от компиляции.
Вызов wcslen должен быть таким:

В примере кода программы, приведенные выше, я использовал strlen, что вызывает ошибки при сборке Unicode.
Приведу пример нерабочего решение с приведением типов языка C:

На сборках Unicode переменная name будет размером 14 байт (7 unicode символов, включая null). Так как строка
«Saturn» содержит только Английские символы, которые можно представить используя ASCII кодирование, Unicode символ ‘S’ будет представлен как [83, 0]. Следующие ASCII символы будут представлены как нули. Заметьте сейчас символ ‘S’ представлен как 2-х байтовое значение 83. Конец строки будет представлен как 2 байта имеющее значение 0.

Итак, когда вы передаете такую строку в strlen, первый символ (то есть первый байт) будет правильным (‘S’ в случае с ‘Saturn’). Но следующий символ/байт будет идентифицирован как конец строки. Поэтому, strlen вернет неправильное значение 1.

Как Вы знаете, Unicode строка может содержать не только Английские символы, и результат strlen будет еще более неопределенным.

Короче говоря приведение типов не будет работать.
Вам придется, либо представлять строки в правильной форме, или использовать функции конвертирования ANSI в Unicode, и обратно.

Теперь, Я надеюсь Вы понимаете следующий код:

Продолжая тему. Вы наверное видели некоторые функции/методы которым нужно передавать количество символов, или возвращающие количество символов. Впрочем есть GetCurrentDirectory, в которую надо передавать число символов, а не количество байт.
Пример:

С другой стороны, если вам нужно выделять память для нужного количества символов, вы должны выделять надлежащее количество байт. В C + +, вы можете просто использовать оператор new:

Но если вы используете функции выделения памяти, такие как malloc, LocalAlloc, GlobalAlloc, и т.д., вы должны указывать количество байт!

Как вы знаете необходимо приведение типа возвращаемого значения. Выражение в аргументе malloc гарантирует, что оно выделяет необходимое количество байт — и выделяет места для нужного количества символов.

Windows Data Types

The data types supported by Windows are used to define function return values, function and message parameters, and structure members. They define the size and meaning of these elements. For more information about the underlying C/C++ data types, see Data Type Ranges.

The following table contains the following types: character, integer, Boolean, pointer, and handle. The character, integer, and Boolean types are common to most C compilers. Most of the pointer-type names begin with a prefix of P or LP. Handles refer to a resource that has been loaded into memory.

For more information about handling 64-bit integers, see Large Integers.

A handle to an object.

This type is declared in WinNT.h as follows:

typedef PVOID HANDLE;

This type is declared in WinDef.h as follows:

typedef HANDLE HBITMAP;

This type is declared in WinDef.h as follows:

typedef HANDLE HBRUSH;

This type is declared in WinDef.h as follows:

typedef HANDLE HCOLORSPACE;

A handle to a dynamic data exchange (DDE) conversation.

This type is declared in Ddeml.h as follows:

typedef HANDLE HCONV;

A handle to a DDE conversation list.

This type is declared in Ddeml.h as follows:

typedef HANDLE HCONVLIST;

This type is declared in WinDef.h as follows:

typedef HICON HCURSOR;

This type is declared in WinDef.h as follows:

typedef HANDLE HDC;

A handle to DDE data.

This type is declared in Ddeml.h as follows:

typedef HANDLE HDDEDATA;

This type is declared in WinDef.h as follows:

typedef HANDLE HDESK;

A handle to an internal drop structure.

This type is declared in ShellApi.h as follows:

typedef HANDLE HDROP;

A handle to a deferred window position structure.

This type is declared in WinUser.h as follows:

typedef HANDLE HDWP;

This type is declared in WinDef.h as follows:

typedef HANDLE HENHMETAFILE;

This type is declared in WinDef.h as follows:

typedef int HFILE;

This type is declared in WinDef.h as follows:

typedef HANDLE HFONT;

A handle to a GDI object.

This type is declared in WinDef.h as follows:

typedef HANDLE HGDIOBJ;

A handle to a global memory block.

This type is declared in WinDef.h as follows:

typedef HANDLE HGLOBAL;

This type is declared in WinDef.h as follows:

typedef HANDLE HHOOK;

This type is declared in WinDef.h as follows:

typedef HANDLE HICON;

A handle to an instance. This is the base address of the module in memory.

HMODULE and HINSTANCE are the same today, but represented different things in 16-bit Windows.

This type is declared in WinDef.h as follows:

typedef HANDLE HINSTANCE;

A handle to a registry key.

This type is declared in WinDef.h as follows:

typedef HANDLE HKEY;

An input locale identifier.

This type is declared in WinDef.h as follows:

typedef HANDLE HKL;

A handle to a local memory block.

This type is declared in WinDef.h as follows:

typedef HANDLE HLOCAL;

This type is declared in WinDef.h as follows:

typedef HANDLE HMENU;

This type is declared in WinDef.h as follows:

typedef HANDLE HMETAFILE;

A handle to a module. The is the base address of the module in memory.

HMODULE and HINSTANCE are the same in current versions of Windows, but represented different things in 16-bit Windows.

This type is declared in WinDef.h as follows:

typedef HINSTANCE HMODULE;

A handle to a display monitor.

This type is declared in WinDef.h as follows:

if(WINVER >= 0x0500) typedef HANDLE HMONITOR;

A handle to a palette.

This type is declared in WinDef.h as follows:

typedef HANDLE HPALETTE;

This type is declared in WinDef.h as follows:

typedef HANDLE HPEN;

The return codes used by COM interfaces. For more information, see Structure of the COM Error Codes. To test an HRESULT value, use the FAILED and SUCCEEDED macros.

This type is declared in WinNT.h as follows:

typedef LONG HRESULT;

This type is declared in WinDef.h as follows:

typedef HANDLE HRGN;

A handle to a resource.

This type is declared in WinDef.h as follows:

typedef HANDLE HRSRC;

A handle to a DDE string.

This type is declared in Ddeml.h as follows:

typedef HANDLE HSZ;

This type is declared in WinDef.h as follows:

typedef HANDLE WINSTA;

This type is declared in WinDef.h as follows:

typedef HANDLE HWND;

A 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.

This type is declared in WinDef.h as follows:

typedef int INT;

A signed integer type for pointer precision. Use when casting a pointer to an integer to perform pointer arithmetic.

This type is declared in BaseTsd.h as follows:

An 8-bit signed integer.

This type is declared in BaseTsd.h as follows:

typedef signed char INT8;

A 16-bit signed integer.

This type is declared in BaseTsd.h as follows:

typedef signed short INT16;

A 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.

This type is declared in BaseTsd.h as follows:

typedef signed int INT32;

A 64-bit signed integer. The range is -9223372036854775808 through 9223372036854775807 decimal.

This type is declared in BaseTsd.h as follows:

typedef signed __int64 INT64;

A language identifier. For more information, see Language Identifiers.

This type is declared in WinNT.h as follows:

typedef WORD LANGID;

A locale identifier. For more information, see Locale Identifiers.

This type is declared in WinNT.h as follows:

typedef DWORD LCID;

A locale information type. For a list, see Locale Information Constants.

This type is declared in WinNls.h as follows:

typedef DWORD LCTYPE;

This type is declared in WinNls.h as follows:

typedef DWORD LGRPID;

A 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.

This type is declared in WinNT.h as follows:

typedef long LONG;

A 64-bit signed integer. The range is -9223372036854775808 through 9223372036854775807 decimal.

This type is declared in WinNT.h as follows:

A signed long type for pointer precision. Use when casting a pointer to a long to perform pointer arithmetic.

This type is declared in BaseTsd.h as follows:

A 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.

This type is declared in BaseTsd.h as follows:

typedef signed int LONG32;

A 64-bit signed integer. The range is -9223372036854775808 through 9223372036854775807 decimal.

This type is declared in BaseTsd.h as follows:

typedef __int64 LONG64;

A message parameter.

This type is declared in WinDef.h as follows:

typedef LONG_PTR LPARAM;

This type is declared in WinDef.h as follows:

typedef BOOL far *LPBOOL;

This type is declared in WinDef.h as follows:

typedef BYTE far *LPBYTE;

This type is declared in WinDef.h as follows:

typedef DWORD *LPCOLORREF;

A pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef __nullterminated CONST CHAR *LPCSTR;

An LPCWSTR if UNICODE is defined, an LPCSTR otherwise. For more information, see Windows Data Types for Strings.

This type is declared in WinNT.h as follows:

A pointer to a constant of any type.

This type is declared in WinDef.h as follows:

typedef CONST void *LPCVOID;

A pointer to a constant null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef CONST WCHAR *LPCWSTR;

This type is declared in WinDef.h as follows:

typedef DWORD *LPDWORD;

This type is declared in WinDef.h as follows:

typedef HANDLE *LPHANDLE;

This type is declared in WinDef.h as follows:

typedef int *LPINT;

This type is declared in WinDef.h as follows:

typedef long *LPLONG;

A pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef CHAR *LPSTR;

An LPWSTR if UNICODE is defined, an LPSTR otherwise. For more information, see Windows Data Types for Strings.

This type is declared in WinNT.h as follows:

A pointer to any type.

This type is declared in WinDef.h as follows:

typedef void *LPVOID;

This type is declared in WinDef.h as follows:

typedef WORD *LPWORD;

A pointer to a null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef WCHAR *LPWSTR;

Signed result of message processing.

This type is declared in WinDef.h as follows:

typedef LONG_PTR LRESULT;

This type is declared in WinDef.h as follows:

typedef BOOL *PBOOL;

This type is declared in WinNT.h as follows:

typedef BOOLEAN *PBOOLEAN;

This type is declared in WinDef.h as follows:

typedef BYTE *PBYTE;

This type is declared in WinNT.h as follows:

typedef CHAR *PCHAR;

A pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef CONST CHAR *PCSTR;

A PCWSTR if UNICODE is defined, a PCSTR otherwise. For more information, see Windows Data Types for Strings.

This type is declared in WinNT.h as follows:

A pointer to a constant null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef CONST WCHAR *PCWSTR;

This type is declared in WinDef.h as follows:

typedef DWORD *PDWORD;

This type is declared in WinNT.h as follows:

typedef DWORDLONG *PDWORDLONG;

This type is declared in BaseTsd.h as follows:

typedef DWORD_PTR *PDWORD_PTR;

This type is declared in BaseTsd.h as follows:

typedef DWORD32 *PDWORD32;

This type is declared in BaseTsd.h as follows:

typedef DWORD64 *PDWORD64;

This type is declared in WinDef.h as follows:

typedef FLOAT *PFLOAT;

This type is declared in BaseTsd.h as follows:

This type is declared in WinNT.h as follows:

typedef HANDLE *PHANDLE;

This type is declared in WinDef.h as follows:

typedef HKEY *PHKEY;

This type is declared in WinDef.h as follows:

typedef int *PINT;

This type is declared in BaseTsd.h as follows:

typedef INT_PTR *PINT_PTR;

This type is declared in BaseTsd.h as follows:

typedef INT8 *PINT8;

This type is declared in BaseTsd.h as follows:

typedef INT16 *PINT16;

This type is declared in BaseTsd.h as follows:

typedef INT32 *PINT32;

This type is declared in BaseTsd.h as follows:

typedef INT64 *PINT64;

This type is declared in WinNT.h as follows:

typedef PDWORD PLCID;

This type is declared in WinNT.h as follows:

typedef LONG *PLONG;

This type is declared in WinNT.h as follows:

typedef LONGLONG *PLONGLONG;

This type is declared in BaseTsd.h as follows:

typedef LONG_PTR *PLONG_PTR;

This type is declared in BaseTsd.h as follows:

typedef LONG32 *PLONG32;

This type is declared in BaseTsd.h as follows:

typedef LONG64 *PLONG64;

A 32-bit pointer. On a 32-bit system, this is a native pointer. On a 64-bit system, this is a truncated 64-bit pointer.

This type is declared in BaseTsd.h as follows:

A 64-bit pointer. On a 64-bit system, this is a native pointer. On a 32-bit system, this is a sign-extended 32-bit pointer.

Note that it is not safe to assume the state of the high pointer bit.

This type is declared in BaseTsd.h as follows:

A signed pointer.

This type is declared in BaseTsd.h as follows:

#define POINTER_SIGNED __sptr

An unsigned pointer.

This type is declared in BaseTsd.h as follows:

#define POINTER_UNSIGNED __uptr

This type is declared in WinNT.h as follows:

typedef SHORT *PSHORT;

This type is declared in BaseTsd.h as follows:

typedef SIZE_T *PSIZE_T;

This type is declared in BaseTsd.h as follows:

typedef SSIZE_T *PSSIZE_T;

A pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef CHAR *PSTR;

This type is declared in WinNT.h as follows:

typedef TBYTE *PTBYTE;

This type is declared in WinNT.h as follows:

typedef TCHAR *PTCHAR;

A PWSTR if UNICODE is defined, a PSTR otherwise. For more information, see Windows Data Types for Strings.

This type is declared in WinNT.h as follows:

This type is declared in WinDef.h as follows:

typedef UCHAR *PUCHAR;

This type is declared in BaseTsd.h as follows:

This type is declared in WinDef.h as follows:

typedef UINT *PUINT;

This type is declared in BaseTsd.h as follows:

typedef UINT_PTR *PUINT_PTR;

This type is declared in BaseTsd.h as follows:

typedef UINT8 *PUINT8;

This type is declared in BaseTsd.h as follows:

typedef UINT16 *PUINT16;

This type is declared in BaseTsd.h as follows:

typedef UINT32 *PUINT32;

This type is declared in BaseTsd.h as follows:

typedef UINT64 *PUINT64;

This type is declared in WinDef.h as follows:

typedef ULONG *PULONG;

This type is declared in WinDef.h as follows:

typedef ULONGLONG *PULONGLONG;

This type is declared in BaseTsd.h as follows:

typedef ULONG_PTR *PULONG_PTR;

This type is declared in BaseTsd.h as follows:

typedef ULONG32 *PULONG32;

This type is declared in BaseTsd.h as follows:

typedef ULONG64 *PULONG64;

This type is declared in WinDef.h as follows:

typedef USHORT *PUSHORT;

A pointer to any type.

This type is declared in WinNT.h as follows:

typedef void *PVOID;

This type is declared in WinNT.h as follows:

typedef WCHAR *PWCHAR;

This type is declared in WinDef.h as follows:

typedef WORD *PWORD;

A pointer to a null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef WCHAR *PWSTR;

A 64-bit unsigned integer.

This type is declared as follows:

typedef unsigned __int64 QWORD;

A handle to a service control manager database. For more information, see SCM Handles.

This type is declared in WinSvc.h as follows:

typedef HANDLE SC_HANDLE;

A lock to a service control manager database. For more information, see SCM Handles.

This type is declared in WinSvc.h as follows:

typedef LPVOID SC_LOCK;

A handle to a service status value. For more information, see SCM Handles.

This type is declared in WinSvc.h as follows:

typedef HANDLE SERVICE_STATUS_HANDLE;

A 16-bit integer. The range is -32768 through 32767 decimal.

This type is declared in WinNT.h as follows:

typedef short SHORT;

The maximum number of bytes to which a pointer can point. Use for a count that must span the full range of a pointer.

This type is declared in BaseTsd.h as follows:

typedef ULONG_PTR SIZE_T;

This type is declared in BaseTsd.h as follows:

typedef LONG_PTR SSIZE_T;

A WCHAR if UNICODE is defined, a CHAR otherwise.

This type is declared in WinNT.h as follows:

A WCHAR if UNICODE is defined, a CHAR otherwise.

This type is declared in WinNT.h as follows:

This type is declared in WinDef.h as follows:

typedef unsigned char UCHAR;

An unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.

This type is declared in BaseTsd.h as follows:

An unsigned INT. The range is 0 through 4294967295 decimal.

This type is declared in WinDef.h as follows:

typedef unsigned int UINT;

This type is declared in BaseTsd.h as follows:

This type is declared in BaseTsd.h as follows:

typedef unsigned char UINT8;

This type is declared in BaseTsd.h as follows:

typedef unsigned short UINT16;

An unsigned INT32. The range is 0 through 4294967295 decimal.

This type is declared in BaseTsd.h as follows:

typedef unsigned int UINT32;

An unsigned INT64. The range is 0 through 18446744073709551615 decimal.

This type is declared in BaseTsd.h as follows:

typedef unsigned __int64 UINT64;

An unsigned LONG. The range is 0 through 4294967295 decimal.

This type is declared in WinDef.h as follows:

typedef unsigned long ULONG;

A 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.

This type is declared in WinNT.h as follows:

This type is declared in BaseTsd.h as follows:

An unsigned LONG32. The range is 0 through 4294967295 decimal.

This type is declared in BaseTsd.h as follows:

typedef unsigned int ULONG32;

An unsigned LONG64. The range is 0 through 18446744073709551615 decimal.

This type is declared in BaseTsd.h as follows:

typedef unsigned __int64 ULONG64;

A Unicode string.

This type is declared in Winternl.h as follows:

An unsigned SHORT. The range is 0 through 65535 decimal.

This type is declared in WinDef.h as follows:

typedef unsigned short USHORT;

An update sequence number (USN).

This type is declared in WinNT.h as follows:

typedef LONGLONG USN;

This type is declared in WinNT.h as follows:

#define VOID void

A 16-bit Unicode character. For more information, see Character Sets Used By Fonts.

This type is declared in WinNT.h as follows:

typedef wchar_t WCHAR;

The calling convention for system functions.

This type is declared in WinDef.h as follows:

#define WINAPI __stdcall

CALLBACK, WINAPI, and APIENTRY are all used to define functions with the __stdcall calling convention. Most functions in the Windows API are declared using WINAPI. You may wish to use CALLBACK for the callback functions that you implement to help identify the function as a callback function.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Data type Description
APIENTRY The calling convention for system functions.
This type is declared in WinDef.h as follows:
#define APIENTRY WINAPI
ATOM An atom. For more information, see About Atom Tables.
This type is declared in WinDef.h as follows:
typedef WORD ATOM;
BOOL A Boolean variable (should be TRUE or FALSE).
This type is declared in WinDef.h as follows:
typedef int BOOL;
BOOLEAN A Boolean variable (should be TRUE or FALSE).
This type is declared in WinNT.h as follows:
typedef BYTE BOOLEAN;
BYTE A byte (8 bits).
This type is declared in WinDef.h as follows:
typedef unsigned char BYTE;
CALLBACK The calling convention for callback functions.
This type is declared in WinDef.h as follows:
#define CALLBACK __stdcall
CALLBACK, WINAPI, and APIENTRY are all used to define functions with the __stdcall calling convention. Most functions in the Windows API are declared using WINAPI. You may wish to use CALLBACK for the callback functions that you implement to help identify the function as a callback function.
CCHAR An 8-bit Windows (ANSI) character.
This type is declared in WinNT.h as follows:
typedef char CCHAR;
CHAR An 8-bit Windows (ANSI) character. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef char CHAR;
COLORREF The red, green, blue (RGB) color value (32 bits). See COLORREF for information on this type.
This type is declared in WinDef.h as follows:
typedef DWORD COLORREF;
CONST A variable whose value is to remain constant during execution.
This type is declared in WinDef.h as follows:
#define CONST const
DWORD A 32-bit unsigned integer. The range is 0 through 4294967295 decimal.
This type is declared in IntSafe.h as follows:
typedef unsigned long DWORD;
DWORDLONG A 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
This type is declared in IntSafe.h as follows:
typedef unsigned __int64 DWORDLONG;
DWORD_PTR An unsigned long type for pointer precision. Use when casting a pointer to a long type to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have been extended to 64 bits in 64-bit Windows.)
This type is declared in BaseTsd.h as follows:
typedef ULONG_PTR DWORD_PTR;
DWORD32 A 32-bit unsigned integer.
This type is declared in BaseTsd.h as follows:
typedef unsigned int DWORD32;
DWORD64 A 64-bit unsigned integer.
This type is declared in BaseTsd.h as follows:
typedef unsigned __int64 DWORD64;
FLOAT A floating-point variable.
This type is declared in WinDef.h as follows:
typedef float FLOAT;
HACCEL A handle to an accelerator table.
This type is declared in WinDef.h as follows:
typedef HANDLE HACCEL;
HALF_PTR Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
This type is declared in BaseTsd.h as follows:

C++
HANDLE