1、在 Linux 實現 Win32 API 之 GetTickCount 函數
為了將 Windows 中的 GetTickCount API 函數移植到 Linux,可以使用如下的代碼:
long GetTickCount()
{
tms tm;
return times(&tm);
}
2、Windows 和 Linux 系統關於 itoa 的移植問題
大家知道,在將 Windows 的 STL 代碼移植到 Linux 系統時,由於 Linux 系統中 STL 沒有實現默認的itoa 函數,因此 itoa 在 Linux 中無法正常工作。要是在 GCC 命令行禁用 STL 的話,那麼代碼裡就無法使用 STL,從而丟失可移植性。這裡給出一個 簡單可行的解決 方法,以便你碰到這種情況時順利進行從 Windows 到 Linux 的移植:
#if defined(__linux__)
#define _itoa itoa
char* itoa(int value, char* str, int radix)
{
int rem = 0;
int pos = 0;
char ch = ''!'' ;
do
{
rem = value % radix ;
value /= radix;
if ( 16 == radix )
{
if( rem >= 10 && rem <= 15 )
{
switch( rem )
{
case 10:
ch = ''a'' ;
break;
case 11:
ch =''b'' ;
break;
case 12:
ch = ''c'' ;
break;
case 13:
ch =''d'' ;
break;
case 14:
ch = ''e'' ;
break;
case 15:
ch =''f'' ;
break;
}
}
}
if( ''!'' == ch )
{
str[pos++] = (char) ( rem + 0x30 );
}
else
{
str[pos++] = ch ;
}
}while( value != 0 );
str[pos] = ''\0'' ;
return strrev(str);
}
#endif
3、Windows 到 Linux 關於 __strrev 的移植問題
因為在 Linux 系統中沒有 __strrev 函數,那麼將 Windows 代碼移植到 Linux 系統時 會有問題,本文下面描述一個技巧,在 Linux 中提供一個替代 __strrev 函數的方法。這裡 提供兩個單獨的實現:一個是普通的 char* C 函數使用的 __strrev 標准實現,另一個是針 對 STL 的實現。兩者的輸入和輸出仍然都是 char*。
//
// strrev 標准版
//
#if !defined(__linux__)
#define __strrev strrev
#endif
char* strrev(char* szT)
{
if ( !szT ) // 處理傳入的空串.
return "";
int i = strlen(szT);
int t = !(i%2)? 1 : 0; // 檢查串長度.
for(int j = i-1 , k = 0 ; j > (i/2 -t) ; j-- )
{
char ch = szT[j];
szT[j] = szT[k];
szT[k++] = ch;
}
return szT;
}
//
// strrev 針對 STL 的版本.
//
char* strrev(char* szT)
{
string s(szT);
reverse(s.begin(), s.end());
strncpy(szT, s.c_str(), s.size());
szT[s.size()+1] = ''\0'';
return szT;
4、實現 Sleep 函數從 Windows 到 Linux 的移植
假設你有一些在 Windows 環境編寫的代碼,你想讓它們在 Linux 環境下運行,條件是要 保持對原有 API署名的調用。比如在 Windows 中有 Sleep,而在 Linux 中對應的函數是 usleep,那麼如何保持原有的函數名稱調用呢?下面給出一段代碼例子:
void Sleep (unsigned int useconds )
{
// 1 毫秒(milisecond) = 1000 微秒 (microsecond).
// Windows 的 Sleep 使用毫秒(miliseconds)
// Linux 的 usleep 使用微秒(microsecond)
// 由於原來的代碼是在 Windows 中使用的,所以參數要有一個毫秒到微秒的轉換。
usleep( useconds * 1000 );
}