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

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

定义.h:

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

void debug_cartesian(struct cartesian_t t);

定义.c

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

主文件

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 中通过引用传递结构:
 void debug_cartesian(struct cartesian_t *t);
 void debug_cartesian(struct cartesian_t *t);

或者

  1. 在 Ada 中通过副本传递记录:

以上是调用以结构为参数的C函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>