映射共享内存块以便在Ada中进行读/写

时间:2015-07-18 17:38:53

标签: ada unchecked-conversion

我在两个进程之间有一个共享内存块(1024字节),我有一个地址指向。我想将一些数据复制到这个共享内存,并在另一个进程上读取它。来自C背景,将记录映射到此地址,然后写入记录似乎最简单,但它似乎没有正确复制。

目前,我正在尝试使用未经检查的转换将指针转换为指向记录的类型,并将其复制到记录中,但是当我将原始有效负载与接收到的有效负载进行比较时,我发现数据存在差异。第二个过程。

这是正确的做法吗?:

type Payload_Array_Type is array (1..255) of Integer_32;

type Common_Buffer_Type is
  record
    Size : Integer_32;
    Payload : Payload_Array_Type;
  end record;

type Common_Buffer_Ptr_Type is access Common_Buffer_Type;

function Convert_Common_Memory_Ptr is new Unchecked_Conversion (
    Source => System.Address,
    Target => Common_Buffer_Ptr_Type);

Common_Memory_Ptr : System.Address;

procedure Copy_To_Common_Buffer
(
    Size : Integer_32;
    Payload : Payload_Array_Type
) is
    Common_Buffer_Ptr : Common_Buffer_Ptr_Type;
begin
    Common_Buffer_Ptr := Convert_Common_Memory_Ptr(Common_Memory_Ptr);
    Common_Buffer_Ptr.Size := Size;
    Common_Buffer_Ptr.Payload(1..255) := Payload(1..255);    
end Copy_To_Common_Buffer;

1 个答案:

答案 0 :(得分:2)

我会尝试这样做:

procedure Payload is 

   type Payload_Array_Type is array (1..255) of Integer_32;

   type Common_Buffer_Type is record
      Size : Integer_32;
      Payload : Payload_Array_Type;
   end record;
   for Common_Buffer_Type use record -- representation clause should be common to both processes
      Size    at 0 range 0 .. 31;
      Payload at 0 range 32 .. 1023;
   end record;
   for Common_Buffer_Type'Size use 1024; -- check this is also used in the other process.

   type Common_Buffer_Ptr_Type is access Common_Buffer_Type;

   Common_Memory_Ptr : System.Address; -- assuming this is where the shared object resides with a real address, possibly make it constant

   procedure Copy_To_Common_Buffer (Size    : in Integer_32;
                    Payload : in Payload_Array_Type) is
      Common_Buffer : Common_Buffer_Type;
      for Common_Buffer'Address use Common_Memory_Ptr; -- address overlay
   begin
      Common_Buffer := (Size => Size,
            Payload => Payload);
   end Copy_To_Common_Buffer;

begin

   Copy_To_Common_Buffer (9,(others => 876));

end Payload;

类型定义应该对两个进程是通用的,并且请注意我使用了一个表示子句来指定组件的位置。

我使用地址覆盖来指定我写作的位置,并一次性写出整个记录。

另请查看@Brian Drummond建议使用pragma volatile。