2014-05-03 64 views
1

如何使用Delphi XE5 FireMonkey執行控制檯/終端應用程序並在OSX和Windows中捕獲輸出。我很想爲這兩個基於Windows的應用程序共享相同的代碼。如何使用Delphi XE5 FireMonkey執行控制檯/終端應用程序並捕獲OSX和Windows中的輸出

+0

你不能有共享代碼。您需要兩個系統的不同代碼。 –

+0

每個系統的代碼是什麼? –

+0

我可以做一個系統,但不能兩個。所以我無法回答。無論如何,這樣的代碼已經存在很多地方。 –

回答

1

對於OSX:

const 
    libc = '/usr/lib/libc.dylib'; 

type 
    PIOFile = Pointer; 

//Create a new stream connected to a pipe running the given command. 
function popen(const Command: PAnsiChar; Modes: PAnsiChar): PIOFile; cdecl; 
    external libc name '_popen'; 

//Close a stream opened by popen and return the status of its child. 
function pclose(Stream: PIOFile): Integer; cdecl; external libc name '_pclose'; 

//Return the EOF indicator for STREAM. 
function feof(Stream: PIOFile): Integer; cdecl; external libc name '_feof'; 

//Read chunks of generic data from STREAM. 
function fread(Ptr: Pointer; Size: LongWord; N: LongWord; 
    Stream: PIOFile): LongWord; cdecl; external libc name '_fread'; 

//Wait for a child to die. When one does, put its status in *STAT_LOC 
//and return its process ID. For errors, return (pid_t) -1. 
function wait(__stat_loc: PInteger): Integer; cdecl; 
    external libc name '_wait'; 

procedure ExecCmdine(const CmdLine: string; CmdResult: TStrings); 
var 
    Output: PIOFile; 
    Buffer: PAnsiChar; 
    TempString: Ansistring; 
    Line: AnsiString; 
    BytesRead: Integer; 
const 
    BufferSize: Integer = 1000; 
begin 
    TempString := ''; 
    Output := popen(PAnsiChar(Ansistring(CmdLine)), 'r'); 
    GetMem(Buffer, BufferSize); 
    if Assigned(Output) then 
    try 
    while feof(Output) = 0 do 
    begin 
     BytesRead := fread(Buffer, 1, BufferSize, Output); 
     SetLength(TempString, Length(TempString) + BytesRead); 
     Move(Buffer^, TempString[length(TempString) - (BytesRead - 1)], BytesRead); 

     while Pos(#10, TempString) > 0 do 
     begin 
     Line := Copy(TempString, 1, Pos(#10, TempString) - 1); 
     if CmdResult <> nil then 
      CmdResult.Add(UTF8ToString(Line)); 

     TempString := Copy(TempString, Pos(#10, TempString) + 1, Length(TempString)); 
     end; 
    end; 
    finally 
    pclose(output); 
    wait(nil); 
    FreeMem(Buffer, BufferSize); 
    end; 
end; 
相關問題