Библиотека TMCLibError — API-документация
Пакет TMC Suite. Маленькая вспомогательная статическая библиотека — «носитель ошибки» (error-object). Язык документации: русский. Все сигнатуры приведены по исходникам из
src/libs/TMCLibError/TmcLibError.cppи заголовкуsrc/Include/TmcLibError.h.
1. Назначение библиотеки
TMCLibError — небольшая вспомогательная библиотека, реализующая паттерн «объект-носитель ошибки» (error-object). Её единственный класс CTmcLibError представляет собой контейнер, который передаётся по ссылке (CTmcLibError&) в методы вычислительных классов других библиотек. Метод, обнаруживший ошибку, записывает в этот объект текстовое сообщение, а вызывающий код затем проверяет факт ошибки и читает сообщение.
Ключевые особенности модели:
- ошибка хранится как текст — строка
CString(а не числовой код); - хранится только последняя ошибка: новое сообщение перезатирает предыдущее;
- нет стека ошибок и нет числовых кодов;
- состояние «есть/нет ошибки» отражает булев флаг
BOOL bIsError.
Важно: библиотека не связана с числовыми кодами ошибок из
Error1.h. Это две независимые подсистемы (см. раздел 7).
Помимо класса, заголовок объявляет две свободные функции генерации временных имён файлов (см. раздел 4).
2. Состав сборки
В сборку TMCLibError.vcxproj входит единственный файл реализации:
| Файл | Назначение |
|---|---|
TmcLibError.cpp |
Реализация класса CTmcLibError и двух свободных функций |
Подключаемый заголовок — ..\..\INCLUDE\TmcLibError.h (общий заголовок пакета, src/Include/TmcLibError.h).
Параметры проекта (TMCLibError.vcxproj):
| Параметр | Значение |
|---|---|
| Platform Toolset | v145 |
| Платформы | Win32, x64 |
| ConfigurationType | StaticLibrary |
| UseOfMfc | Static (в конфигурации Release) |
| CharacterSet | MultiByte |
| Подключаемый property sheet | build\LibOutput.props |
Поскольку
UseOfMfc=StaticиCharacterSet=MultiByte, библиотека использует классы MFC (в частностиCString) и компилируется в многобайтовой (не Unicode) кодировке.
Старый файл проекта формата .vcproj (legacy) в настоящей документации не рассматривается.
3. Класс CTmcLibError
Объявлен в TmcLibError.h, реализован в TmcLibError.cpp.
class CTmcLibError
{
public:
void PutErrorMessage( char *pszErrorMessage );
void PutErrorMessage( CString csErrorMessage );
CString GetErrorMessage( void );
BOOL IsError( void );
void Clear( void );
CTmcLibError& operator=( CTmcLibError& cError1 );
CTmcLibError();
public:
virtual ~CTmcLibError();
private:
CString csError;
BOOL bIsError;
};
3.1. Назначение класса
CTmcLibError — контейнер состояния ошибки. Экземпляр создаётся в «чистом» состоянии (ошибки нет), затем передаётся по ссылке в вычислительные методы; те при необходимости вызывают PutErrorMessage(...). Вызывающий код использует IsError() и GetErrorMessage().
3.2. Поля (private)
| Поле | Тип | Смысл | Допустимые значения |
|---|---|---|---|
csError |
CString |
Текст последнего сообщения об ошибке | Любая строка; по умолчанию "Error:no" (макрос CTMCRTHERROR_0000) |
bIsError |
BOOL |
Флаг наличия ошибки | FALSE — ошибки нет; TRUE — ошибка установлена |
Оба поля закрыты (private) и доступны только через публичные методы.
3.3. Публичные методы
CTmcLibError()
CTmcLibError();
Конструктор. Приводит объект в состояние «ошибки нет»:
- устанавливает
bIsError = FALSE; -
инициализирует
csErrorстрокой"Error:no"(черезcsError.Format(CTMCRTHERROR_0000)). -
Параметры: нет.
- Возврат: нет (конструктор).
virtual ~CTmcLibError()
virtual ~CTmcLibError();
Деструктор. Тело пустое (return;) — никаких ресурсов вручную не освобождается (память CString освобождается самим MFC). Объявлен virtual, что допускает корректное удаление через указатель на базовый класс при наследовании.
- Параметры: нет.
- Возврат: нет (деструктор).
void Clear( void )
void Clear( void );
Сброс состояния ошибки в исходное:
bIsError = FALSE;csError←"Error:no"(CTMCRTHERROR_0000).
В теле метода присутствуют закомментированные отладочные вызовы AfxMessageBox (трассировочные сообщения "Trace0", "Trace1", "Trace2") — в рабочей сборке они неактивны.
- Параметры: нет.
- Возврат:
void.
BOOL IsError( void )
BOOL IsError( void );
Проверка наличия ошибки.
- Параметры: нет.
- Возврат: значение поля
bIsError(TRUE— ошибка установлена,FALSE— ошибки нет).
void PutErrorMessage( CString csErrorMessage )
void PutErrorMessage( CString csErrorMessage );
Установить ошибку, передав сообщение как объект CString.
- устанавливает
bIsError = TRUE; -
присваивает
csError = csErrorMessage. -
Параметры:
csErrorMessage(CString) — текст сообщения об ошибке.- Возврат:
void. - Поведение: перезаписывает любое предыдущее сообщение (хранится только последнее).
void PutErrorMessage( char *pszErrorMessage )
void PutErrorMessage( char *pszErrorMessage );
Перегрузка: установить ошибку, передав сообщение как C-строку.
- устанавливает
bIsError = TRUE; -
формирует
csErrorчерезcsError.Format( "%s", pszErrorMessage ). -
Параметры:
pszErrorMessage(char*) — указатель на строку с завершающим нулём.- Возврат:
void. - Поведение: перезаписывает предыдущее сообщение.
О неактивной перегрузке
PutErrorMessage( char *pszErrorMessage, ... ). ВTmcLibError.cppприсутствует полностью закомментированный вариант с переменным числом аргументов и форматированием черезvsprintf(с буфером длиныCTMCRTHERROR_STRLENMAX). Он не объявлен в заголовке и не компилируется — упомянут здесь лишь для полноты. В рабочей сборке этого метода нет.
CString GetErrorMessage( void )
CString GetErrorMessage( void );
Получить текст последней ошибки.
- Параметры: нет.
- Возврат: значение поля
csError(CString). Если ошибка не устанавливалась, вернётся строка по умолчанию"Error:no". - Примечание: метод возвращает значение независимо от
bIsError; для корректной интерпретации сначала проверяйтеIsError().
CTmcLibError& operator=( CTmcLibError& cError1 )
CTmcLibError& operator=( CTmcLibError& cError1 );
Оператор присваивания. Копирует состояние ошибки из cError1 в текущий объект:
bIsError = cError1.IsError();-
csError.Format( "%s", cError1.GetErrorMessage() ); -
Параметры:
cError1(CTmcLibError&) — объект-источник (передаётся по неконстантной ссылке).- Возврат:
CTmcLibError&— ссылка на текущий объект (*this), что допускает цепочки присваиваний.
4. Свободные функции
Объявлены в TmcLibError.h и реализованы в TmcLibError.cpp. К классу CTmcLibError отношения не имеют — это утилиты формирования временных имён файлов.
void MakeTempFileNameForBzCalcMn( CString& csTplFileName )
void MakeTempFileNameForBzCalcMn( CString & csTplFileName );
Дописывает к переданному имени файла суффикс "_for_Bz_Mn" (в конец строки, через +=).
- Параметры:
csTplFileName(CString&) — имя файла; модифицируется на месте (in/out).- Возврат:
void(результат — в самом параметре). - Назначение (по имени): формирование временного имени файла для расчёта составляющей Bz (вариант «минус»,
Mn).
void MakeTempFileNameForBzCalcPl( CString& csTplFileName )
void MakeTempFileNameForBzCalcPl( CString & csTplFileName );
Дописывает к переданному имени файла суффикс "_for_Bz_Pl".
- Параметры:
csTplFileName(CString&) — имя файла; модифицируется на месте (in/out).- Возврат:
void(результат — в самом параметре). - Назначение (по имени): формирование временного имени файла для расчёта составляющей Bz (вариант «плюс»,
Pl).
5. Макросы заголовка
Определены в TmcLibError.h.
| Макрос | Значение | Где используется |
|---|---|---|
CTMCRTHERROR_0000 |
"Error:no" |
Используется — в конструкторе и Clear() как «нет ошибки» |
CTMCRTHERROR_0001 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0002 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0003 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0004 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0005 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0006 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0007 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0008 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0009 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_0010 |
"Error:" |
Объявлен, не используется |
CTMCRTHERROR_STRLENMAX |
512 |
Использовался только в закомментированном vsprintf-варианте PutErrorMessage (см. раздел 3.3); в активном коде не применяется |
Все макросы CTMCRTHERROR_0001..CTMCRTHERROR_0010 имеют одно и то же значение "Error:" и нигде не задействованы.
6. Схема хранения и передачи ошибок
Модель ошибки в TMCLibError предельно проста:
- Состояние = одна строка
CString csError+ один флагBOOL bIsError. - Только последняя ошибка. Нет стека, нет истории, нет числовых кодов — повторный вызов
PutErrorMessage(...)перезатирает предыдущий текст.
Типовая схема передачи (по ссылке). Объект CTmcLibError создаётся вызывающим кодом и передаётся по ссылке CTmcLibError& в методы вычислительных классов, например (сигнатуры — из библиотеки TMCIndan, использующей TMCLibError):
Read( CString& , CTmcLibError& );
IsCorrectly( CTmcLibError& );
Search_1Param( ... , CTmcLibError& );
Внутри такого метода при ошибке вызывается:
cError.PutErrorMessage( "текст ошибки" );
Вызывающий код после возврата проверяет состояние:
if( cError.IsError() )
{
CString msg = cError.GetErrorMessage();
// вывести / обработать сообщение
}
Связи с числовыми кодами Error1.h в этой схеме нет — сообщение всегда текстовое.
7. Зависимости
MFC. Реализация подключает stdafx.h (который, как правило, тянет afx.h / afxwin.h). Из MFC используются:
CString— хранение и форматирование текста ошибки и имён файлов;BOOL— флаг состояния;AfxMessageBox— только в закомментированном отладочном кодеClear().
Заголовок TmcLibError.h напрямую подключает <cstringt.h> (объявление CString-классов ATL/MFC). Строка #include <windows.h> в заголовке закомментирована.
Не используются библиотеки пакета: complex, exprint, PREPR, SFILE95 — прямых #include из них в TMCLibError нет.
Отдельная подсистема Error1.h — НЕ связана с TMCLibError. Error1.h — это независимая legacy-подсистема обработки ошибок с числовыми кодами и функциями вроде put_error_messege, SetErrorFileName (с атрибутами _far / _fortran — наследие win16). К классу CTmcLibError она отношения не имеет. Эти две системы не следует путать: CTmcLibError хранит ошибку как текст, Error1.h оперирует числовыми кодами.
8. Использование
Линковка ядрами. Оба счётных ядра — PlanarRT_H (tmc_rth.exe) и PlanarRT_X (tmc_rtx.exe) — указывают TMCLibError.lib в AdditionalDependencies (вместе с sfile95, prepr, exprint, TMCIndan).
Фактическое применение — в библиотеке TMCIndan. Хотя ядра линкуются с TMCLibError.lib напрямую, класс CTmcLibError реально используется внутри библиотеки TMCIndan, которая, в свою очередь, используется ядрами. Места применения (по исходникам TMCIndan):
TmcRTH_IndanTopology.cpp;TmcRTH_IndanParam.cpp;TmcRTH_IndanOutput.cpp;FieldIntegrated.cpp— методCFieldIntegrated::GetError()возвращаетCTmcLibError&(объект-носитель ошибки отдаётся вызывающему по ссылке).
Не путать с CTmcTtoS. Во вьюверах есть отдельный, похожий по смыслу класс CTmcTtoS (TmcTtoS.cpp) с полями того же назначения (bIsError / csError). Это не CTmcLibError и не часть библиотеки TMCLibError — совпадает лишь идея «носителя ошибки». Их следует различать.
The TMCLibError library — API documentation
TMC Suite package. A small auxiliary static library — an "error carrier" (error-object). All signatures are taken from the sources in
src/libs/TMCLibError/TmcLibError.cppand the headersrc/Include/TmcLibError.h.
1. Purpose of the library
TMCLibError is a small auxiliary library that implements the "error-carrier
object" pattern (error-object). Its single class CTmcLibError is a container
passed by reference (CTmcLibError&) into the methods of the computational
classes of other libraries. A method that detects an error writes a text message
into this object, and the calling code then checks for the fact of the error and
reads the message.
Key features of the model:
- the error is stored as text — a
CStringstring (not a numeric code); - only the last error is stored: a new message overwrites the previous one;
- there is no error stack and no numeric codes;
- the "error present / absent" state is reflected by the boolean flag
BOOL bIsError.
Important: the library is not related to the numeric error codes from
Error1.h. These are two independent subsystems (see section 7).
Besides the class, the header declares two free functions that generate temporary file names (see section 4).
2. Build composition
The TMCLibError.vcxproj build contains a single implementation file:
| File | Purpose |
|---|---|
TmcLibError.cpp |
The implementation of the CTmcLibError class and the two free functions |
The included header is ..\..\INCLUDE\TmcLibError.h (the package's shared header,
src/Include/TmcLibError.h).
Project parameters (TMCLibError.vcxproj):
| Parameter | Value |
|---|---|
| Platform Toolset | v145 |
| Platforms | Win32, x64 |
| ConfigurationType | StaticLibrary |
| UseOfMfc | Static (in the Release configuration) |
| CharacterSet | MultiByte |
| Included property sheet | build\LibOutput.props |
Since
UseOfMfc=StaticandCharacterSet=MultiByte, the library uses MFC classes (in particularCString) and is compiled in a multibyte (non-Unicode) encoding.
The old project file in .vcproj format (legacy) is not considered in this
documentation.
3. The CTmcLibError class
Declared in TmcLibError.h, implemented in TmcLibError.cpp.
class CTmcLibError
{
public:
void PutErrorMessage( char *pszErrorMessage );
void PutErrorMessage( CString csErrorMessage );
CString GetErrorMessage( void );
BOOL IsError( void );
void Clear( void );
CTmcLibError& operator=( CTmcLibError& cError1 );
CTmcLibError();
public:
virtual ~CTmcLibError();
private:
CString csError;
BOOL bIsError;
};
3.1. Purpose of the class
CTmcLibError is an error-state container. An instance is created in a "clean"
state (no error), then passed by reference into computational methods; those call
PutErrorMessage(...) when necessary. The calling code uses IsError() and
GetErrorMessage().
3.2. Fields (private)
| Field | Type | Meaning | Allowed values |
|---|---|---|---|
csError |
CString |
The text of the last error message | Any string; by default "Error:no" (the CTMCRTHERROR_0000 macro) |
bIsError |
BOOL |
The error-present flag | FALSE — no error; TRUE — an error is set |
Both fields are private and accessible only through the public methods.
3.3. Public methods
CTmcLibError()
CTmcLibError();
The constructor. Brings the object into the "no error" state:
- sets
bIsError = FALSE; -
initializes
csErrorwith the string"Error:no"(viacsError.Format(CTMCRTHERROR_0000)). -
Parameters: none.
- Return: none (a constructor).
virtual ~CTmcLibError()
virtual ~CTmcLibError();
The destructor. Its body is empty (return;) — no resources are freed manually
(the CString memory is freed by MFC itself). It is declared virtual, which
allows correct deletion through a base-class pointer under inheritance.
- Parameters: none.
- Return: none (a destructor).
void Clear( void )
void Clear( void );
Resets the error state to the initial one:
bIsError = FALSE;csError←"Error:no"(CTMCRTHERROR_0000).
The method body contains commented-out debugging calls to AfxMessageBox
(tracing messages "Trace0", "Trace1", "Trace2") — they are inactive in the
production build.
- Parameters: none.
- Return:
void.
BOOL IsError( void )
BOOL IsError( void );
Checks for the presence of an error.
- Parameters: none.
- Return: the value of the
bIsErrorfield (TRUE— an error is set,FALSE— no error).
void PutErrorMessage( CString csErrorMessage )
void PutErrorMessage( CString csErrorMessage );
Set an error by passing the message as a CString object.
- sets
bIsError = TRUE; -
assigns
csError = csErrorMessage. -
Parameters:
csErrorMessage(CString) — the text of the error message.- Return:
void. - Behavior: overwrites any previous message (only the last one is stored).
void PutErrorMessage( char *pszErrorMessage )
void PutErrorMessage( char *pszErrorMessage );
An overload: set an error by passing the message as a C string.
- sets
bIsError = TRUE; -
forms
csErrorviacsError.Format( "%s", pszErrorMessage ). -
Parameters:
pszErrorMessage(char*) — a pointer to a null-terminated string.- Return:
void. - Behavior: overwrites the previous message.
About the inactive overload
PutErrorMessage( char *pszErrorMessage, ... ). InTmcLibError.cppthere is a fully commented-out variant with a variable number of arguments and formatting viavsprintf(with a buffer of lengthCTMCRTHERROR_STRLENMAX). It is not declared in the header and does not compile — it is mentioned here only for completeness. This method is absent from the production build.
CString GetErrorMessage( void )
CString GetErrorMessage( void );
Get the text of the last error.
- Parameters: none.
- Return: the value of the
csErrorfield (CString). If no error was set, the default string"Error:no"is returned. - Note: the method returns the value regardless of
bIsError; for correct interpretation, checkIsError()first.
CTmcLibError& operator=( CTmcLibError& cError1 )
CTmcLibError& operator=( CTmcLibError& cError1 );
The assignment operator. Copies the error state from cError1 into the current
object:
bIsError = cError1.IsError();-
csError.Format( "%s", cError1.GetErrorMessage() ); -
Parameters:
cError1(CTmcLibError&) — the source object (passed by non-const reference).- Return:
CTmcLibError&— a reference to the current object (*this), which allows chained assignments.
4. Free functions
Declared in TmcLibError.h and implemented in TmcLibError.cpp. They have no
relation to the CTmcLibError class — they are utilities for forming temporary
file names.
void MakeTempFileNameForBzCalcMn( CString& csTplFileName )
void MakeTempFileNameForBzCalcMn( CString & csTplFileName );
Appends the suffix "_for_Bz_Mn" to the passed file name (at the end of the
string, via +=).
- Parameters:
csTplFileName(CString&) — the file name; modified in place (in/out).- Return:
void(the result is in the parameter itself). - Purpose (by the name): forming a temporary file name for computing the Bz
component (the "minus" variant,
Mn).
void MakeTempFileNameForBzCalcPl( CString& csTplFileName )
void MakeTempFileNameForBzCalcPl( CString & csTplFileName );
Appends the suffix "_for_Bz_Pl" to the passed file name.
- Parameters:
csTplFileName(CString&) — the file name; modified in place (in/out).- Return:
void(the result is in the parameter itself). - Purpose (by the name): forming a temporary file name for computing the Bz
component (the "plus" variant,
Pl).
5. Header macros
Defined in TmcLibError.h.
| Macro | Value | Where used |
|---|---|---|
CTMCRTHERROR_0000 |
"Error:no" |
Used — in the constructor and Clear() as "no error" |
CTMCRTHERROR_0001 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0002 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0003 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0004 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0005 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0006 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0007 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0008 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0009 |
"Error:" |
Declared, not used |
CTMCRTHERROR_0010 |
"Error:" |
Declared, not used |
CTMCRTHERROR_STRLENMAX |
512 |
Used only in the commented-out vsprintf variant of PutErrorMessage (see section 3.3); not applied in the active code |
All the macros CTMCRTHERROR_0001..CTMCRTHERROR_0010 have the same value
"Error:" and are not used anywhere.
6. The scheme of storing and passing errors
The error model in TMCLibError is extremely simple:
- State = one
CString csErrorstring + oneBOOL bIsErrorflag. - Only the last error. There is no stack, no history, no numeric codes — a
repeated call of
PutErrorMessage(...)overwrites the previous text.
The typical passing scheme (by reference). A CTmcLibError object is created by
the calling code and passed by reference CTmcLibError& into the methods of
computational classes, for example (the signatures are from the TMCIndan library,
which uses TMCLibError):
Read( CString& , CTmcLibError& );
IsCorrectly( CTmcLibError& );
Search_1Param( ... , CTmcLibError& );
Inside such a method, on an error the following is called:
cError.PutErrorMessage( "error text" );
After the return the calling code checks the state:
if( cError.IsError() )
{
CString msg = cError.GetErrorMessage();
// display / handle the message
}
There is no connection with the numeric codes of Error1.h in this scheme —
the message is always text.
7. Dependencies
MFC. The implementation includes stdafx.h (which usually pulls in afx.h /
afxwin.h). From MFC the following are used:
CString— storing and formatting the error text and file names;BOOL— the state flag;AfxMessageBox— only in the commented-out debugging code ofClear().
The header TmcLibError.h directly includes <cstringt.h> (the declaration of the
ATL/MFC CString classes). The line #include <windows.h> in the header is
commented out.
The package libraries complex, exprint, PREPR, SFILE95 are not
used — there are no direct #includes from them in TMCLibError.
The separate Error1.h subsystem is NOT related to TMCLibError. Error1.h is
an independent legacy error-handling subsystem with numeric codes and functions like
put_error_messege, SetErrorFileName (with the _far / _fortran attributes —
a win16 legacy). It has no relation to the CTmcLibError class. These two
systems should not be confused: CTmcLibError stores the error as text, Error1.h
operates on numeric codes.
8. Usage
Linking by the kernels. Both compute kernels — PlanarRT_H (tmc_rth.exe)
and PlanarRT_X (tmc_rtx.exe) — list TMCLibError.lib in
AdditionalDependencies (together with sfile95, prepr, exprint, TMCIndan).
Actual use — in the TMCIndan library. Although the kernels link against
TMCLibError.lib directly, the CTmcLibError class is actually used inside the
TMCIndan library, which in turn is used by the kernels. The places of use (from
the TMCIndan sources):
TmcRTH_IndanTopology.cpp;TmcRTH_IndanParam.cpp;TmcRTH_IndanOutput.cpp;FieldIntegrated.cpp— theCFieldIntegrated::GetError()method returns aCTmcLibError&(the error-carrier object is given to the caller by reference).
Do not confuse with CTmcTtoS. The viewers have a separate class of similar
meaning, CTmcTtoS (TmcTtoS.cpp), with fields of the same purpose (bIsError
/ csError). It is not CTmcLibError and not part of the TMCLibError
library — only the idea of an "error carrier" coincides. They should be
distinguished.