Friday, May 22, 2009

Datatype convertion

integer to TCHAR array
----------------
TCHAR szStatic[32];
wsprintf(szStatic,_T("%d min(s)"),dwValue);

integer to char array
----------------
char szStatic[32];
sprintf(szStatic,"%d min(s)",dwValue);


CString to char *
----------------
char *szPic=new char[csPic.GetLength()+1] ;
sprintf(szPic,"%S",csPic.GetBuffer(0));

char array to cstring
----------------
char strString[] = "this is a char string";
CString cstring;
cstring = CString( strString );

char array to STL string
---------------------
char buffer[] = "senthil";
string sValue;
sValue.assign((char*)buffer);

LPCSTR to LPCTSTR ( anscii to unicode conversion )
----------------------------------------
LPCSTR psz="senthil";
LPCTSTR m_ptsz=NULL;

const int size = MultiByteToWideChar(CP_ACP, 0, psz, -1, NULL, 0);

if (size == 0) {

ASSERT(!_T("Function \"MultiByteToWideChar\" failed."));
}
m_ptsz = new WCHAR [(sizeof(WCHAR)*size)];
VERIFY(MultiByteToWideChar(CP_ACP, 0, psz, -1, (LPWSTR)m_ptsz, size) != 0);
delete [] m_ptsz;
m_ptsz = NULL;

Dll creation

creation of win32 dll

step 1:
create a win32 project with the name Sampledll

step 2:
A Sampledll.cpp file will be created with Dllmain function
BOOL APIENTRY DllMain(HMODULE hModule,DWORD reason_for_call,LPVOID lpReserved )
{
return TRUE;
}

step 3:
create a .h file named Sampledll.h and expotable APIs and callback function

#ifdef VISUALIMITSINTERFACE_EXPORTS // in the project settings,c++ ->preprocessor we can find this macro
#define MY_DLL DLLEXPORT
#else
#define MY_DLL DLLIMPORT
#endif

typedef void (*fun2)(int, int);
extern "C" MY_DLL int fun1( int a , int b);
extern "C" MY_DLL int fun3(char* sz1,fun2 fpfun2);

step 4:

In the Sampledll.cpp , write exportable function defintions
extern "C" DLLEXPORT int fun1( int a , int b){... ..return n;}
extern "C" DLLEXPORT int fun3(char* sz1,fun2 fpfun2){....fpfun2(i,n); // callback function that used to call a function in Exe
}

step 5:
create a Exe application

Include the file Sampledll.h

Instead of .. extern "C" MY_DLL int fun1( int a , int b);
, we can add the following lines
typedef void (*pfnfun2)(int, int); // callback function
typedef int (*pfnfun1)(char* ,char* );typedef int (*pfnfun3)(char*,pfnfun2);

step 6:

In the SampleDlg.h file declare this

pfnfun1 fun1;
pfnfun3 fun3;

step 7:

In the SampleDlg.cpp file add this callback function

void SampleCallBack(int n, int y)
{
return;
}

In a function call this API to set callback function for the dll

void CVisuaLimitsServerDlg::OnBnClickedBtnTransfer()
{
fun3(szResult,&SampleCallBack);
}

Using Loadlibrary we can load the dll

m_hInstance = LoadLibrary(L"Sampledll.dll");

if (m_hInstance)
{
fun1 = (pfnfun1) GetProcAddress (m_hInstance, "fun1");
fun3 = (pfnfun3) GetProcAddress (m_hInstance, "fun3");
}