调用以结构作为参数的 C 函数

Calling a C-Function which takes a structure as argument

我被困在这个我认为很简单的问题上。我有一个结构定义和一个采用该结构实例的函数。我如何在 Ada 中调用这个函数?这是一个示例代码:

defines.h :

typedef struct cartesian_t
{
    float x;
    float y;
    float z;
} cartesian_t;

void debug_cartesian(struct cartesian_t t);

defines.c

void debug_cartesian(struct cartesian_t t)
{
    printf("%f, %f, %f\n", t.x, t.y, t.z);
}

main.adb

with Interfaces.C; use Interfaces.C;
with Ada.Text_IO;

procedure Main is
    type Cartesian_Record_Type is record
        X : C_Float;
        Y : C_Float;
        Z : C_Float;
    end record
    with
        Convention => C;
        
    procedure Debug_Cartesian(Cart : in Cartesian_Record_Type)
    with
        Import => True,
        Convention => C,
        External_Name => "debug_cartesian";


    T : Cartesian_Record_Type := (
        X => 5.0,
        Y => 1.0,
        Z => -1.0
    );
begin
    Debug_Cartesian(T);
end Main_Union;

输出不是我所期望的。它应该是“5.0、1.0、-1.0”,但内存中显然有错误,因为我得到了随机值。就像将数据放在 C 期望的位置之外。

RM B.3 中有一个实施建议,始终通过引用传递记录。至少 GNAT 遵循了这个建议。

要避免这种情况,您有两种选择:

  1. 在 C:
  2. 中通过引用传递结构
 void debug_cartesian(struct cartesian_t *t);

  1. 在 Ada 中通过副本传递记录:
    end record
    with
       Convention => C_Pass_By_Copy;