c - 如何读取 Ada 中的 C Void 指针?

标签 c pointers buffer ada void-pointers

有以下以 void 指针为参数的 C 函数:

int read(void *buf, size_t num);

int => 返回读取操作是否成功。
void *buf => c void 无符号字节缓冲区指针作为函数参数。
size_t num => 应填充的字节缓冲区的大小。

目前我有以下 Ada 实现:

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;

Buffer_Array 没有按预期填满。 如果一些 Ada 爱好者有一些提示或想法,那就太好了。

最佳答案

假设 Ada 私有(private)类型 System.Address 和 C 指针兼容是极其不可移植和不必要的。使用约定 C 声明类型,将 out 参数声明为 out 参数:

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

关于c - 如何读取 Ada 中的 C Void 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65531680/

相关文章:

c - GNU gdb 如何显示源文件名和符号行

c - 如何在 C 语言中为 Pascal 子集编译器生成符号表?

c++ - 可变大小指针数组

c - 为什么要将 40 添加到传递给 LocalAlloc 的大小中?

go - 将缓冲区写入文件不会返回错误,那么为什么文件后记为空?

C、函数返回另一个函数

c++ - 我正在寻找一个紧凑的C/C++编译器;任何建议?

c - 如何将命令行输入的行存储到 C 的缓冲区中?

c - 嵌套结构分配/释放导致崩溃

c - 指针游戏数组不知道如何将指针向后移动