2

I'm a beginner at Ada and most of the resources online are all in C and I'm having a difficult time translating over into Ada.

Should I use SysV shm with shmget and shmat or should I use POSIX shm with mmap and shm_open?

Can you give me an example of an Ada program with these two procedures (write, then read)? Say I want to write and then read the string "Butterflies", for example.

Thanks a million!

rici
  • 234,347
  • 28
  • 237
  • 341

1 Answers1

2

There's several methods that you could do this. Perhaps the easiest is memory overlays. Let's say that you reserve a block of memory $3300 to $33FF, what you could do use the byte at $3300 to indicate the length of the string, with $3301..$33FF as the contents of the string.

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;

Then for memory overlay:

Overlayed_String : ShortString.String(255)
  with Import, Address => System.Storage_Elements.To_Address( 16#3300# );
Shark8
  • 4,095
  • 1
  • 17
  • 31