我如何在Ada中使用Linux写入然后读取任意字符串到共享内存?

时间:2018-08-06 16:56:37

标签: shared-memory ada

我是Ada的初学者,在线上的大多数资源都用C编写,我很难转换成Ada。

我应该将SysV shm与shmget和shmat一起使用还是应该将POSIX shm与mmap和shm_open一起使用?

您能给我一个带有这两个过程(先写,再读)的Ada程序的例子吗?例如,假设我要编写然后读取字符串“ Butterflies”。

感谢一百万!

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。也许最简单的是内存覆盖。假设您为$3300保留了一块内存$33FF,可以使用$3300使用$3301处的字节来指示字符串的长度。 $33FF作为字符串的内容。

With Interfaces;
    Package ShortString is
        Type String( Length : Interfaces.Unsigned_8 ) is private;

        -- Convert a shortstring to a standard string.
        Function "+"( Input : String ) Return Standard.String;

        -- Convert a standard string to a short-string.
        Function "+"( Input : Standard.String ) Return String
          with Pre => Input'Length <= Positive(Interfaces.Unsigned_8'Last);

        Private

        -- Declare a Positive subtype for a byte.
        Subtype Positive is Interfaces.Unsigned_8 range 1..Interfaces.Unsigned_8'Last;

        -- Use the byte-sized positive for indexing the short-string.
        Type Internal is Array(Positive range <>) of Character;

        -- Declare a varying-length record for the short-string implementation.
        Type String( Length : Interfaces.Unsigned_8 ) is record
            Data : Internal(1..Length);
        end record;

        -- We must ensure the first byte is the length.
        For String use record
          Length at 0 range 0..7;
        end record;

        Function "+"( Input : String ) Return Standard.String is
          ( Standard.String(Input.Data) );

        Function "+"( Input : Standard.String ) Return String is
          ( Length => Interfaces.Unsigned_8(Input'Length),
            Data   => Internal( Input )
          );
    End ShortString;

然后进行内存覆盖:

Overlayed_String : ShortString.String(255)
  with Import, Address => System.Storage_Elements.To_Address( 16#3300# );