2

I am compiling my application in Delphi XE2.It was developed in delphi 7.. My code is as follows:

type
 Name = array[0..100] of PChar;
 PName = ^Name;
var
  HEnt: pHostEnt;
  HName: PName;
  WSAData: TWSAData;
  i: Integer;

begin
     Result := False;
     if WSAStartup($0101, WSAData) <> 0 then begin
     WSAErr := 'Winsock is not responding."';
       Exit;
     end;
    IPaddr := '';
    New(HName);


 if GetHostName(HName^, SizeOf(Name)) = 0 then <-----ERROR
   begin
      HostName := StrPas(HName^);      

      HEnt := GetHostByName(HName^);    
            "
            "
         so on...
   end;

When i try to compile the code ,i get the following error: enter image description here

When i try this code in another application it works fine in Delphi 7. How do i convert from character pointer to PAnsiChar type to make it run on Delphi XE2??.

Mohammed Nasman
  • 10,992
  • 7
  • 43
  • 68
poonam
  • 748
  • 4
  • 19
  • 40

3 Answers3

6

My Delphi knowledge might be a little rusty, but as far as I remember:

PChar is (kind of like, not exactly) a pointer to a string in itself, so this type is actually an array of 101 PChars (strings):

Name = array[0..100] of PChar;

I think you should change it to array [0..100] of Char, or why not declare HName as a PAnsiChar right from the start?

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
  • If i declare it as array of char then it gives same error. and if HName is declare as PAnsiChar then it says "Incompatible types:PAnsiChar and AnsiChar". – poonam Jun 06 '12 at 11:06
6

This is not the correct way to use gethostname(). Use this instead:

var
  HName: array[0..100] of AnsiChar;
  HEnt: pHostEnt;
  WSAData: TWSAData;
  i: Integer;
begin
  Result := False;
  if WSAStartup($0101, WSAData) <> 0 then begin
    WSAErr := 'Winsock is not responding."';
    Exit;
  end;
  IPaddr := '';

  if gethostname(HName, SizeOf(Name)) = 0 then
  begin
    HostName := StrPas(HName);
    HEnt := gethostbyname(HName);
    ...
  end;
  ...
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
2

yes...i got it:) I declared HName as HName:PAnsiChar; and

if GetHostName(PAnsiChar(HName^), SizeOf(Name)) = 0 
HostName := StrPas(PAnsiChar(HName^)); 
HEnt := GetHostByName(PAnsiChar(HName^));     
poonam
  • 748
  • 4
  • 19
  • 40