- 論壇徽章:
- 0
|
幾個(gè) Windows 到 Linux 的代碼移植問(wèn)題
編譯:
Northtibet
1、在 Linux 實(shí)現(xiàn) Win32 API 之 GetTickCount 函數(shù)
為了將 Windows 中的 GetTickCount API 函數(shù)移植到 Linux,可以使用如下的代碼:
long GetTickCount()
{
tms tm;
return times(&tm);
}
2、Windows 和 Linux 系統(tǒng)關(guān)于 itoa 的移植問(wèn)題
大家知道,在將 Windows 的 STL 代碼移植到 Linux 系統(tǒng)時(shí),由于 Linux 系統(tǒng)中 STL 沒(méi)有實(shí)現(xiàn)默認(rèn)的 itoa
函數(shù),因此 itoa 在 Linux 中無(wú)法正常工作。要是在 GCC 命令行禁用 STL 的話,那么代碼里就無(wú)法使用 STL,從而丟失可移植性。這里給出一個(gè)
簡(jiǎn)單可行的解決方法,以便你碰到這種情況時(shí)順利進(jìn)行從
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
3、Windows 到 Linux 關(guān)于 __strrev 的移植問(wèn)題
因?yàn)樵?Linux 系統(tǒng)中沒(méi)有 __strrev 函數(shù),那么將 Windows 代碼移植到 Linux 系統(tǒng)時(shí)會(huì)有問(wèn)題,本文下面描述一個(gè)技巧,在
Linux 中提供一個(gè)替代 __strrev 函數(shù)的方法。這里提供兩個(gè)單獨(dú)的實(shí)現(xiàn):一個(gè)是普通的 char* C 函數(shù)使用的 __strrev
標(biāo)準(zhǔn)實(shí)現(xiàn),另一個(gè)是針對(duì) STL 的實(shí)現(xiàn)。兩者的輸入和輸出仍然都是 char*。//
// strrev 標(biāo)準(zhǔn)版
//
#if !defined(__linux__)
#define __strrev strrev
#endif
char* strrev(char* szT)
{
if ( !szT ) // 處理傳入的空串.
return "";
int i = strlen(szT);
int t = !(i%2)? 1 : 0; // 檢查串長(zhǎng)度.
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 針對(duì) 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、實(shí)現(xiàn) Sleep 函數(shù)從 Windows 到 Linux 的移植
假設(shè)你有一些在 Windows 環(huán)境編寫(xiě)的代碼,你想讓它們?cè)?Linux 環(huán)境下運(yùn)行,條件是要保持對(duì)原有 API署名的調(diào)用。比如在 Windows
中有 Sleep,而在 Linux 中對(duì)應(yīng)的函數(shù)是 usleep,那么如何保持原有的函數(shù)名稱調(diào)用呢?下面給出一段代碼例子:void Sleep(unsigned int useconds )
{
// 1 毫秒(milisecond) = 1000 微秒 (microsecond).
// Windows 的 Sleep 使用毫秒(miliseconds)
// Linux 的 usleep 使用微秒(microsecond)
// 由于原來(lái)的代碼是在 Windows 中使用的,所以參數(shù)要有一個(gè)毫秒到微秒的轉(zhuǎn)換。
usleep( useconds * 1000 );
}
本文來(lái)自ChinaUnix博客,如果查看原文請(qǐng)點(diǎn):http://blog.chinaunix.net/u1/55468/showart_2124887.html |
|