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

How do I write and then read an arbitrary string to shared memory using Linux in Ada?

我是 Ada 的初学者,大多数在线资源都是用 C 语言编写的,我很难将其翻译成 Ada。

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

你能给我一个包含这两个过程(写,然后读)的 Ada 程序的例子吗?例如,假设我要写入然后读取字符串 "Butterflies"。

万分感谢!

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

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# );