当前位置:首页 > linux教程 > 列表

几个Windows到Linux的代码移植问题

发布:smiling 来源: PHP粉丝网  添加日期:2014-03-06 22:11:38 浏览: 评论:0 

1、在Linux实现Win32 API之GetTickCount函数

为了将Windows中的GetTickCount API函数移植到Linux,可以使用如下的代码:

  1. long GetTickCount() 
  2. { 
  3. tms tm; 
  4. return times(&tm); 
  5. } 

2、Windows和Linux系统关于itoa的移植问题

大家知道,在将Windows的STL代码移植到Linux系统时,由于Linux系统中STL没有实现默认的itoa函数,因此itoa在Linux中无法正常工作。要是在GCC命令行禁用STL的话,那么代码里就无法使用STL,从而丢失可移植性。这里给出一个简单可行的解决方法,以便你碰到这种情况时顺利进行从Windows到Linux的移植:

  1. #if defined(__linux__) 
  2. #define _itoa   itoa 
  3. char* itoa(int value, char*  str, int radix) 
  4. { 
  5. int  rem = 0; 
  6. int  pos = 0; 
  7. char ch  = ''!'' ; 
  8. do 
  9. { 
  10. rem    = value % radix ; 
  11. value /= radix; 
  12. if ( 16 == radix ) 
  13. { 
  14. if( rem >= 10 && rem <= 15 ) 
  15. { 
  16. switch( rem ) 
  17. { 
  18. case 10: 
  19. ch = ''a'' ; 
  20. break; 
  21. case 11: 
  22. ch =''b'' ; 
  23. break; 
  24. case 12: 
  25. ch = ''c'' ; 
  26. break; 
  27. case 13: 
  28. ch =''d'' ; 
  29. break; 
  30. case 14: 
  31. ch = ''e'' ; 
  32. break; 
  33. case 15: 
  34. ch =''f'' ; 
  35. break; 
  36. } 
  37. } 
  38. } 
  39. if( ''!'' == ch ) 
  40. { 
  41. str[pos++] = (char) ( rem + 0x30 ); 
  42. } 
  43. else 
  44. { 
  45. str[pos++] = ch ; 
  46. } 
  47. }while( value != 0 ); 
  48. str[pos] = '''' ; 
  49. return strrev(str); 
  50. } 
  51. #endif 

3、Windows到Linux关于__strrev的移植问题

因为在Linux系统中没有__strrev函数,那么将Windows代码移植到Linux系统时会有问题,本文下面描述一个技巧,在Linux中提供一个替代__strrev函数的方法。这里提供两个单独的实现:一个是普通的char* C函数使用的__strrev标准实现,另一个是针对STL的实现。两者的输入和输出仍然都是char*。

  1. // 
  2. // strrev 标准版 
  3. // 
  4. #if !defined(__linux__) 
  5. #define __strrev strrev 
  6. #endif 
  7. char* strrev(char* szT) 
  8. { 
  9. if ( !szT )                 // 处理传入的空串. 
  10. return ""; 
  11. int i = strlen(szT); 
  12. int t = !(i%2)? 1 : 0;      // 检查串长度. 
  13. for(int j = i-1 , k = 0 ; j > (i/2 -t) ; j-- ) 
  14. { 
  15. char ch  = szT[j]; 
  16. szT[j]   = szT[k]; 
  17. szT[k++] = ch; 
  18. } 
  19. return szT; 
  20. } 
  21. // 
  22. // strrev 针对 STL 的版本. 
  23. // 
  24. char* strrev(char* szT) 
  25. { 
  26. string s(szT); 
  27. reverse(s.begin(), s.end()); 
  28. strncpy(szT, s.c_str(), s.size()); 
  29. szT[s.size()+1] = ''''; 
  30. return szT; 

4、实现Sleep函数从Windows到Linux的移植

假设你有一些在Windows环境编写的代码,你想让它们在Linux环境下运行,条件是要保持对原有API署名的调用。比如在Windows中有Sleep,而在Linux中对应的函数是usleep,那么如何保持原有的函数名称调用呢?下面给出一段代码例子:

  1. void Sleep(unsigned int useconds ) 
  2. { 
  3. // 1 毫秒(milisecond) = 1000 微秒 (microsecond). 
  4. // Windows 的 Sleep 使用毫秒(miliseconds) 
  5. // Linux 的 usleep 使用微秒(microsecond) 
  6. // 由于原来的代码是在 Windows 中使用的,所以参数要有一个毫秒到微秒的转换。 
  7. usleep( useconds * 1000 ); 
  8. } 

Tags: Windows Linux 代码移植

分享到: