【问题标题】:How To Read an C Void pointer in Ada?如何在 Ada 中读取 C Void 指针?
【发布时间】:2021-04-08 09:59:36
【问题描述】:

有以下以空指针为参数的C-Function:

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 爱好者有一些提示或想法,那就太好了。

【问题讨论】:

  • “没有按预期填满” - 实际发生了什么?您使用的是什么操作系统? read() 导入哪个库?
  • 输出:读取成功 0 0 0 0 0 0 0 0 0 0 OS:Slackware14.04 64位,读取是一个例子,但我想从openssl.org/docs/man1.1.1/man3/SSL_read.html导入SSL_read
  • SSL_read 现在可以使用。 Ada 代码没有任何问题。这是我自己的 c 示例函数的错误 c 实现。感谢 Simon 看一下代码。

标签: c pointers buffer ada void-pointers


【解决方案1】:

假设 Ada 私有类型 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");

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2012-05-23
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2010-12-08
    相关资源
    最近更新 更多