在delphi2010中调用gethostname函数出现错误:E2010 Incompatible types: 'Array' and 'PAnsiChar'...

一个获取本机ip的函数:

 

 1  class  function TGlobal.GetLocalIP:  string;
 2  type TaPInAddr =  array [ 0.. 10of PInAddr; 
 3  PaPInAddr = ^TaPInAddr; 
 4  var phe : PHostEnt; 
 5     pptr : PaPInAddr; 
 6     Buffer :  array [ 0.. 63of char;
 7     I : Integer; 
 8      GInitData : TWSADATA; 
 9  begin 
10     WSAStartup($ 101,ginitdata); 
11     result :=  ''
12     gethostname(buffer,sizeof(buffer));
13     phe := gethostbyname(buffer); 
14     if phe = nil  then exit; 
15    pptr := papinaddr(phe^.h_addr_list); 
16    I :=  0
17    while pptr^[i] <>  nil  do 
18    begin 
19  result := SysUtils.StrPas(inet_ntoa(pptr^[i]^)); 
20  inc(I); 
21     end
22   WSACleanup; 
23  end ;

在delphi2007下编译没有问题。在delphi2010下编译出现错误:E2010 Incompatible types: 'Array' and 'PAnsiChar'

错误定位在第12行。也就是调用gethostname函数出现了错误。根源在于在delphi2010中,gethostname函数的原型发生了改变:

由原来的:function gethostname(name: PChar; len: Integer): Integer; stdcall;

变成了:  function gethostname(name: PAnsiChar; len: Integer): Integer; stdcall;

 

函数做如下修改,编译通过:

 

 1  function GetLocalIP:  string;
 2  type
 3   TaPInAddr =  array [ 0.. 10of PInAddr;
 4   PaPInAddr = ^TaPInAddr;
 5  const
 6   SIZE_HOSTNAME= 250;
 7  var
 8   phe       : PHostEnt;
 9   pptr      : PaPInAddr;
10   LStr      : AnsiString;
11   I         : Integer;
12   GInitData : TWSADATA;
13  begin
14   WSAStartup($ 101,ginitdata);
15   result :=  '';
16   SetLength(LStr, SIZE_HOSTNAME);
17   gethostname (PAnsiChar(LStr), SIZE_HOSTNAME);
18   phe := gethostbyname(PAnsiChar(LStr));
19    if phe = nil  then exit;
20   pptr := papinaddr(phe^.h_addr_list);
21   I :=  0;
22    while pptr^[i] <>  nil  do
23    begin
24     result := SysUtils.StrPas(inet_ntoa(pptr^[i]^));
25     inc(I);
26    end;
27   WSACleanup;
28  end ;

 

 

 

 

 

 

转载于:https://www.cnblogs.com/lance2088/archive/2012/09/03/2669016.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值