Programming Reference | Static variables 12.6 Static variables | Static variables Memory allocation between Windows and real-time context in conjunction with static variables If global instances are used, be aware of the following: A maximum of 128 global instances may exist in total. It should be noted that global instances can also be used by TwinCAT's own modules. If the number is exceeded, the destructors are no longer called. From TwinCAT 3.1 4026, a message is displayed in the "Output" of the engineering if the limit is exceeded: Too many static objects detected on shutdown of class factory .tmx. Max Number of static objects exceeded by N item(s). This may result in a memory leak.
The program code can query the currently used or available global instances: #include "CrtInit.h" int overflow = cppGetNumberHandlerOverflow(); int free = TcCrtGetFreeNumberAtexitHandler(); Memory allocated in the real-time context must be released in the OS transition, for example, so that this does not happen via the destructor. When the constructor is executed, TwinCAT system resources cannot yet be accessed, because the connection via the Classfactory to the TcCOM object server has not yet been established. Below you will see how to deal with this. This code includes three examples of global instances: class MyClassA { public: MyClassA() {} ~MyClassA() {} private:
int v; } MyClassA A; class MyClassB { static MyClassA Value; }; MyClassA& GetInstance() { static MyClassA a; return a; } Singletons for the initialization of global instances In order to delay the time, global or so-called singleton instances can also be created as local static objects. It is very important when using global class instances that the destructors are called late and at this point there is no longer a connection to the TwinCAT system, so that TwinCAT resources must be released beforehand. Here is a sample code showing a singleton in TwinCAT: #include "TcInterfaces.h" class VersionProvider : public ITcVersionProvider { public:
DECLARE_IUNKNOWN_NODELETE() VersionProvider() { m_Version = { 1, 2, 3, 0}; } virtual HRESULT TCOMAPI GetVersion(T_Version& version) { TwinCAT 3 152 Version: 1.19.1