跳到內容

Ada 程式設計/庫/介面

來自華夏公益教科書,開放的書籍,開放的世界

Ada. Time-tested, safe and secure.
Ada. 經久耐用,安全可靠。

Interfaces 包有助於與其他程式語言進行介面。Ada 是少數將與其他語言的介面作為語言標準一部分的語言之一。語言標準定義了與 CCobolFortran 的介面。當然,任何實現都可能定義進一步的介面——例如,GNAT 定義了與 C++ 的介面。

實際上,與其他語言的介面由以下內容提供pragma Export,pragma Importpragma Convention.

在 Ada 2012 中,這些子句具有使用 "with" 代替 "pragma" 的替代形式。

例如,以下是一個完整程式,它查詢 Unix 系統上的 terminfo(終端資訊)資料庫以獲取當前終端視窗的尺寸。它與 ncurses 包中的 C 語言函式進行介面,因此它必須在編譯時與 ncurses 連結(例如,使用 -lncurses 開關)。

 with Ada.Text_IO;
 with Interfaces.C;
 with Interfaces.C.Pointers;
 with Interfaces.C.Strings;
 
 procedure ctest is
   use  Interfaces.C;
 
   type int_array is array (size_t range <>) of aliased int with Pack;
 
   package Int_Pointers is new Pointers (
     Index              => size_t,
     Element            => int,
     Element_Array      => int_array,
     Default_Terminator => 0
   );
 
   -- int setupterm (char *term, int fildes, int *errret);
   function Get_Terminal_Data (
     terminal           : Interfaces.C.Strings.chars_ptr; 
     file_descriptor    : int; 
     error_code_pointer : Int_Pointers.Pointer
   ) return int
   with Import => True, Convention => C, External_Name => "setupterm";
 
   -- int tigetnum (char *name);
   function Get_Numeric_Value (name : Interfaces.C.Strings.chars_ptr) return int
   with Import => True, Convention => C, External_Name => "tigetnum";
 
   function Format (value : int) return String is
     result : String := int'Image (value);
   begin
     return (if result(1) = ' ' then result(2..result'Last) else result);
   end Format;
 
   error_code         : aliased int;
   error_code_pointer : Int_Pointers.Pointer := error_code'Access;
 
 begin
   if Get_Terminal_Data (Interfaces.C.Strings.Null_Ptr, 1, error_code_pointer) = 0 then
     Ada.Text_IO.Put_Line (
       "Window size: " &
       Format (Get_Numeric_Value (Interfaces.C.Strings.New_String ("cols"))) & "x" & 
       Format (Get_Numeric_Value (Interfaces.C.Strings.New_String ("lines")))
     );
   else
     Ada.Text_IO.Put_Line ("Can't access terminal data");
   end if;
 end ctest;

華夏公益教科書

[編輯 | 編輯原始碼]

Ada 參考手冊

[編輯 | 編輯原始碼]
華夏公益教科書