网站地图    收藏   

主页 > 系统 > linux系统 >

几个Windows到Linux的代码移植问题 - linux教程

来源:自学PHP网    时间:2014-11-28 23:06 作者: 阅读:

[导读] 1、在Linux实现Win32 API之GetTickCount函数为了将Windows中的GetTickCount API函数移植到Linux,可以使用如下的代码:longGetTickCount(...

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

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

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

  1. long GetTickCount() 
  2. tms tm; 
  3. return times(&tm); 

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. int  rem = 0; 
  5. int  pos = 0; 
  6. char ch  = ''!'' ; 
  7. do 
  8. rem    = value % radix ; 
  9. value /= radix; 
  10. if ( 16 == radix ) 
  11. if( rem >= 10 && rem <= 15 ) 
  12. switch( rem ) 
  13. case 10: 
  14. ch = ''a'' ; 
  15. break
  16. case 11: 
  17. ch =''b'' ; 
  18. break
  19. case 12: 
  20. ch = ''c'' ; 
  21. break
  22. case 13: 
  23. ch =''d'' ; 
  24. break
  25. case 14: 
  26. ch = ''e'' ; 
  27. break
  28. case 15: 
  29. ch =''f'' ; 
  30. break
  31. if''!'' == ch ) 
  32. str[pos++] = (char) ( rem + 0x30 ); 
  33. else 
  34. str[pos++] = ch ; 
  35. }while( value != 0 ); 
  36. str[pos] = '''' ; 
  37. return strrev(str); 
  38. #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. if ( !szT )                 // 处理传入的空串. 
  9. return ""
  10. int i = strlen(szT); 
  11. int t = !(i%2)? 1 : 0;      // 检查串长度. 
  12. for(int j = i-1 , k = 0 ; j > (i/2 -t) ; j-- ) 
  13. char ch  = szT[j]; 
  14. szT[j]   = szT[k]; 
  15. szT[k++] = ch; 
  16. return szT; 
  17. // 
  18. // strrev 针对 STL 的版本. 
  19. // 
  20. char* strrev(char* szT) 
  21. string s(szT); 
  22. reverse(s.begin(), s.end()); 
  23. strncpy(szT, s.c_str(), s.size()); 
  24. szT[s.size()+1] = ''''
  25. return szT; 

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

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

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

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论