我正在try 让Ada代码编译成可在C中调用的DLL,到目前为止,我已经设法使其适用于简单类型,如整数,但对于更复杂的类型,如数组或记录/ struct ,我遇到了困难.
下面是我的记录/ struct 的Ada代码.它是一个动态库,我使用命令"gprBuild-p../Math.gpr-p"将其编译为DLL:
person.adb
with Interfaces.C; use Interfaces.C;
package body Person is
function Set_Age_To_Five(P : Person_Record) return Person_Record is
Result : Person_Record;
begin
Result := P;
Result.Age := 5;
return Result;
end Set_Age_To_Five;
end Person;
Person.ads
with Interfaces.C; use Interfaces.C;
package Person is
type Person_Record is record
Name : String(1 .. 100);
Age : Interfaces.C.int;
Address : String(1 .. 100);
end record with Convention => C_Pass_By_Copy;
function Set_Age_To_Five(P : Person_Record) return Person_Record;
pragma Export (C, Set_Age_To_Five, "Set_Age_To_Five");
end Person;
Math.gpr
library project Math is
for Languages use ("Ada");
for Library_Name use "Person";
for Source_Dirs use ("src");
for Object_Dir use "obj";
for Library_Dir use "lib";
for Library_Kind use "Dynamic";
end Math;
然后我有一个C头文件math.h:
#ifndef MATH_H
#define MATH_H
#ifdef __cplusplus
extern "C"
#endif
typedef struct {
char Name[101];
int Age;
char Address[101];
} Person_Record;
Person_Record Set_Age_To_Five(Person_Record P);
#ifdef __cplusplus
#endif
#endif /* MATH_H */
最后是我的C代码:
#include <stdio.h>
#include "math.h"
int main() {
Person_Record p, q, r;
// Initialize the person record
snprintf(p.Name, sizeof(p.Name), "John");
p.Age = 25;
snprintf(p.Address, sizeof(p.Address), "123 Main St");
// Call the Set_Age_To_Five function from the DLL
q = Set_Age_To_Five(p);
// Print the modified person record
printf("Name: %s\n", q.Name);
printf("Age: %d\n", q.Age);
printf("Address: %s\n", q.Address);
return 0;
}
这在执行时应该返回
Name: John
Age: 5
Address: 123 Main St
相反,它的回归:
Name: John
Age: 25
Address: 123 Main St
我try 过通过变量传递,通过引用传递.在ADA中使用约定C和约定传递c.