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] = '''' ;
- 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] = '''';
- 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 );
- }
新聞熱點
疑難解答