zoukankan      html  css  js  c++  java
  • 在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 ;
  • 相关阅读:
    servlet
    过滤器
    拦截器
    logback
    hibernate(1)
    函数的关键字参数
    函数的不定长参数
    打印星形三角
    九九乘法表
    udp客户端收发数据流程
  • 原文地址:https://www.cnblogs.com/lance2088/p/2669016.html
Copyright © 2011-2022 走看看