从Ada访问c常量 [英] Access c constant from Ada
问题描述
我有一个具有这样类型定义的头文件
I have a header file with a type definition like this
#ifndef SETSIZE
#define SETSIZE 32
#endif
typedef struct _set {
unsigned array[SETSIZE];
} set_t;
要使用相应的C函数,我需要在Ada中提供set_t类型。问题在于SETSIZE是可配置的参数(默认值为32)。如果我理解正确,则无法从Ada访问预处理程序定义。
可以在c文件中添加一个常量,并在Ada中像这样使用它:
To use a corresponding C-function I need to have the set_t type available in Ada. The problem is that SETSIZE is a configurable parameter (with default value 32). If I understand it correctly I cannot access preprocessor defines from Ada. Would it be possible to add a constant to the c-file and use this in Ada like this:
#ifndef SETSIZE
#define SETSIZE 32
#endif
const size_t test = SETSIZE;
// Alternative
enum { test2 = SETSIZE };
--Ada--
-- import test somehow
type set_array is array (0 .. test) of aliased Interfaces.C.unsigned;
type set_t is record
array_field : aliased set_array;
end record;
或通过其他任何方式在Ada中正确使用此类型,而无需对原始C-代码
Or any other way to have this type correctly available in Ada without too much change in the original C-code
推荐答案
为什么不简单:
SetSize: constant Interfaces.C.Size_T;
pragma Import(
Convention => C,
Entity => SetSize,
External_Name => "set_size"
);
并在您的 C
文件中:
const size_t set_size = SETSIZE;
使用 gnatmake 4.8.1
进行了测试:
// File: set_def.c
#include <stdlib.h>
#ifndef SETSIZE
#define SETSIZE 32
#endif
const size_t set_size = SETSIZE ;
typedef struct _set {
unsigned array[SETSIZE];
} set_t;
编译 set_def.c
:
Z:\> gcc -c set_def.c
-- File: main.adb
with Interfaces.C, Ada.Text_IO, Ada.Integer_Text_IO ;
procedure Main is
use type Interfaces.C.Size_T ; -- To have access to the - operator
SetSize: constant Interfaces.C.Size_T;
pragma Import (
Convention => C,
Entity => SetSize,
External_Name => "set_size"
);
-- Note that you should go to SetSize - 1
type Set_Array is array(0 .. SetSize - 1) of aliased Interfaces.C.Unsigned;
type Set_T is
record
Array_Field: aliased Set_Array;
end record;
MySet: Set_T := (Array_Field => (1, 2, 3, others => 0));
begin
Ada.Integer_Text_IO.Put (Integer(SetSize), 0); Ada.Text_IO.New_Line;
Ada.Integer_Text_IO.Put (MySet.Array_Field'Length, 0); Ada.Text_IO.New_Line;
for I in MySet.Array_Field'range loop
Ada.Integer_Text_IO.Put (Integer(MySet.Array_Field(I)), 0);
Ada.Text_IO.Put(' ');
end loop;
end Main;
编译 main.adb
并与 set_def.o
:
Z:\> gnatmake main.adb -largs set_def.o
Z:\> main.exe
32
32
1 2 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
这篇关于从Ada访问c常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!