Home

hersto:  Usefull Code Snippets (for C++)

 

Rant to the author:

    

Check for a response

These are a few code blocks that i like to insert in in programs here and there because they simply make my live easier. Most of them are in C++ (all, currently)

Quick Access:
Just type this into the address bar:     http://www.hersto.com/CodeSnippets

 

 

SizeOf(.)

#define SizeOf(A)  ( sizeof(A) / sizeof(*(A)) )

Not so lengthy casts for C++

While i like the casts in C++ a lot due to their detailed-ness, they destroy the text flow ( :-) ) because they are so lengthy. They are also to type a lot. Therefore i'm using these abbreviations.

#define S_Cast static_cast
#define R_Cast reinterpret_cast
#define D_Cast dynamic_cast
#define C_Cast const_cast
#define O_Cast(T, E) ((T)(E)) // "old cast"

CSprintf(.)

CString CSprintf(LPCTSTR Format, ...)
{
    va_list Args;
    va_start(Args, Format);

    CString Res;
    Res.FormatV(Format, Args);

return Res;
}

MsgBox(.)

void MsgBox(LPCTSTR Format, ...)
{
    va_list Args;
    va_start(Args, Format);

    CString Msg;
    Res.FormatV(Format, Args);

    MessageBox(Msg);
    // or:
    ::MessageBox(NULL, Msg, whateverYouLikeHere, MB_OK); // TBD: adopt to your needs.
}

GetModuleHandle(.)

HMODULE GetModuleHandle()
{
    // Uses code and info from
    //   http://www.codeguru.com/Cpp/W-P/dll/tips/article.php/c3635/
    //   http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
    // and
    //   http://msdn.microsoft.com/library/en-us/dllproc/base/dllmain.asp
    // The last one is the documentation page about DllMain(.), which says that the base address
    // is the module handle (ergo this is documented.)

    // TBD: The above code from http://www.codeguru.com/Cpp/W-P/dll/tips/article.php/c3635/
    // seams to provide a faster way with VC 7, i.e. without any function call to Win32.
    // Should we use that, or is the VirtualQuery(.) method ok?

    static HMODULE shModule= NULL;
    static bool sbHaveAsked= false;

    if(!sbHaveAsked)
    {
        static char sSomething;

        MEMORY_BASIC_INFORMATION Info= {0};
        SIZE_T rc= ::VirtualQuery(&sSomething, &Info, sizeof(Info));

        shModule= reinterpret_cast<HMODULE>(Info.AllocationBase);

        sbHaveAsked= true;
    }

return shModule;


    // Found on the Net:
    /*
    #if _MSC_VER >= 1300    // for VC 7.0
        // from ATL 7.0 sources
        #ifndef _delayimp_h
        extern "C" IMAGE_DOS_HEADER __ImageBase;
        #endif
    #endif

    HMODULE GetCurrentModule()
    {
    #if _MSC_VER < 1300    // earlier than .NET compiler (VC 6.0)

        // Here's a trick that will get you the handle of the module
        // you're running in without any a-priori knowledge:
        // http://www.dotnet247.com/247reference/msgs/13/65259.aspx

        MEMORY_BASIC_INFORMATION mbi;
        static int dummy;
        VirtualQuery( &dummy, &mbi, sizeof(mbi) );

        return reinterpret_cast<HMODULE>(mbi.AllocationBase);

    #else    // VC 7.0

        // from ATL 7.0 sources

        return reinterpret_cast<HMODULE>(&__ImageBase);
    #endif
    }
    */
}

GetInstallDir

Requires GetModuleHandle(.).
Returns the directory of the module that contains GetModuleHandle(.).

CString GetInstallDir()
{
    char Buffer[MAX_PATH];
    ::GetModuleFileName(GetModuleHandle(), Buffer, SizeOf(Buffer));

    char* pBS= strrchr(Buffer, '\\');
    if(pBS)
        *pBS= '\0';

return Buffer;
}

mfGetNodeFieldFromBSContact(.)

//
// #include "ref.h"
// (#define _COM)
//
__QueryIfcResult CSomeContactContainer_Wnd::mfGetNodeFieldFromBSContact( const char*  NodeName
                                                                       , const char*  FieldName
                                                                       , const IID&   IID
                                                                       )
{
    ref<IUnknown> refUnkNode= m_Contact.getNode(NodeName);
    if(!refUnkNode)
return NULL;

    refUnkNode->Release(); // We got one ref count too much in the above line.
    if(!refUnkNode)
return NULL;

    ref<Node> refNode= refUnkNode.Query(IID_Node);
    if(!refNode)
return NULL;

    ref<Field> refField;
    BSTR wFieldName= ((CString) FieldName).AllocSysString();
    refNode->getField(wFieldName, &refField.Expose());
    ::SysFreeString(wFieldName);
    if(!refField)
return NULL;

return refField.Query(IID);
}

CreateUniqueTempFile(.)

HANDLE CreateUniqueTempFile(CString Prefix, CString Ext, CString* pFileName= NULL)
{
    CString TempPath;
    int TempPathLen= GetTempPath(0, NULL) + 1;
    GetTempPath(TempPathLen, TempPath.GetBuffer(TempPathLen));
    TempPath.ReleaseBuffer();
    if(TempPath.GetAt(TempPath.GetLength() - 1) == '\\')
        TempPath= TempPath.Left(TempPath.GetLength() - 1);



    // TBD: Error checking?

    int Id= ((rand() & 0xffff) + (rand() & 0xffff) * 0x10000) % 123456789; // two times 
                                 // rand % 0xffff because RAND_MAX is 0x8000 i beleive.
                                 //  it's quick, and dirty, but that's enough for here.

    while(true)
    {
        CString FileName= CSprintf("%s\\%s-%08x.%s", &*TempPath, &*Prefix, Id, &*Ext);

        HANDLE hFile= CreateFile( FileName
                                , FILE_WRITE_DATA
                                , 0 // We don't share access to this file (are the only opener)
                                , NULL
                                , CREATE_NEW
                                , FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN
                                , NULL
                                );
        if(hFile != INVALID_HANDLE_VALUE)
        {
            if(pFileName)
                *pFileName= FileName;
return hFile;
        }

        Id+= rand() % 7;
    }
}

FileExists(.)

bool FileExists(CString Path)
{
    WIN32_FIND_DATA FileInfo= {0};

    const HANDLE hFind= FindFirstFile(Path, &FileInfo);
    FindClose(hFind);

return hFind != INVALID_HANDLE_VALUE;
}

 

__.-.__
end of document