幾個Windows到Linux的代碼移植問題

來源:互聯網
上載者:User

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 );
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.