mcxbain
mcxbain

Reputation: 101

How To Read an C Void pointer in Ada?

There is Following C-Function with void pointer as Argument:

int read(void *buf, size_t num);

int => returns if the read operation was successfully or not.
void *buf => c void unsigned byte buffer pointer as function argument.
size_t num => size of the byte buffer which should be filled up.

Currently I have the following Ada Implementation:

with Ada.Text_IO;
with System;
with Interfaces.C;

use Ada.Text_IO;
use Interfaces.C;

procedure Main is

      -- Imported C function
      function Read(Buf:System.Address; Num:int) return int;
      pragma Import(C, Read, "read");

      -- Byte Array Type
      type Byte_Type is mod 2**8;
      for Byte_Type'Size use 8;

      type Byte_Array_Type is array(Positive range <>) of Byte_Type;

      -- Initialize
      Buffer_Check:int;
      Buffer_Size:Positive:=10;
      Buffer_Array:Byte_Array_Type(1 .. Buffer_Size):=(others => 0); --initialise array with zero
           
     
   begin
      
      Buffer_Check:=Read(Buffer_Array'Address, int(Buffer_Size));

      if Buffer_Check /= 0 then

         Put_Line("Read success");

         for K in Buffer_Array'First .. Buffer_Array'Last loop

            Put_Line(Integer'Image(Integer(Byte_Type(Buffer_Array(K)))));

         end loop;

      else
         
         Put_Line("Read Failed");
         
      end if;
      
end Main;

The Buffer_Array doesn't get filled up as expected. It would be Great if some Ada Enthusiast have some hint or Idea.

Upvotes: 3

Views: 587

Answers (1)

Jeffrey R. Carter
Jeffrey R. Carter

Reputation: 3358

Assuming that an Ada private type System.Address and a C pointer are compatible is extremely non-portable and unnecessary. Declare your types with convention C and your out parameter as an out parameter:

pragma Convention (C, Byte_Type);
pragma Convention (C, Byte_Array_Type);

function Read (Buf : out Byte_Array_Type; Num : in int) return int;
pragma Import (C, Read, "read");

Upvotes: 5

Related Questions