在mfc中打开console窗口,备忘。
1 console.h
#ifndef __Console_H__ #define __Console_H__ #include < stdio.h > #include < stdlib.h > #include < stdarg.h > #include < io.h > #include < Windows.h > class Console : public Singleton < ARCConsole > { public : Console() { if ( ! m_hConsoleOutput) { AllocConsole(); m_hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); char str[ 512 ] = " start Console Log...\n " ; WriteConsole(m_hConsoleOutput, str, strlen(str),NULL, NULL); } } void printf( const char * format, ...) { va_list args; int len = 0 ; char str[ 512 ] = { 0 }; va_start(args, format); len = vsprintf(str, format, args) + 1 ; WriteConsole(m_hConsoleOutput, str, len,NULL, NULL); va_end(args); return ; } ~ Console() { if (m_hConsoleOutput) { char str[ 512 ] = " destroy console...\n " ; WriteConsole(m_hConsoleOutput, str, strlen(str),NULL, NULL); CloseHandle(m_hConsoleOutput); FreeConsole(); } } static ARCConsole & getSingleton( void ) { assert( ms_Singleton ); return ( * ms_Singleton ); } static ARCConsole * getSingletonPtr( void ) { return ms_Singleton; } protected : static HANDLE m_hConsoleOutput; }; template <> Console * Ogre::Singleton < Console > ::ms_Singleton = 0 ; HANDLE Console::m_hConsoleOutput = 0 ; extern Console _G_Console; Console _G_Console;
偷懒继承了ogre里的singleton类。若不同的lib分别创建了实例,子类记得覆盖父类的getSingleton()和getSingletonPtr()2个函数。
|
2 singleton.h
template < typename T > class Singleton { private : /* * \brief Explicit private copy constructor. This is a forbidden operation. */ Singleton( const Singleton < T > & ); /* * \brief Private operator= . This is a forbidden operation. */ Singleton & operator = ( const Singleton < T > & ); protected : static T * ms_Singleton; public : Singleton( void ) { assert( ! ms_Singleton ); #if defined( _MSC_VER ) && _MSC_VER < 1200 int offset = ( int )(T * ) 1 - ( int )(Singleton < T >* )(T * ) 1 ; ms_Singleton = (T * )(( int ) this + offset); #else ms_Singleton = static_cast < T * > ( this ); #endif } ~ Singleton( void ) { assert( ms_Singleton ); ms_Singleton = 0 ; } static T & getSingleton( void ) { assert( ms_Singleton ); return ( * ms_Singleton ); } static T * getSingletonPtr( void ) { return ms_Singleton; } };