Reputation: 49
I am trying to access a string declared in a C program from an Ada subprogram, but I get a segmentation fault. Would anyone be able to help me fix this?
Here's an example of what fails, it seems that the segfault comes from the call to Interfaces.C.Strings.Value
in ada_decs.adb, but I'm not sure why, or how I can make it work.
The backtrace from gdb shows:
#0 0x00000000004167ea in system.secondary_stack.ss_mark ()
#1 0x00000000004037e6 in ada_print_it (s=0x427244 "Hello") at (...)/ada_decs.adb:2
#2 0x000000000040327c in main (argc=1, argv=0x7fffffffe568) at (...)/main.c:5
(with (...)
signifying the full file path).
ada_decs.ads:
with Interfaces.C.Strings;
with Ada.Text_IO;
package Ada_Decs is
procedure Print_It (s : Interfaces.C.Strings.chars_ptr) with
Export => True,
Convention => C,
External_Name => "ada_print_it";
end Ada_Decs;
ada_decs.adb:
package body Ada_Decs is
procedure Print_It (s : Interfaces.C.Strings.chars_ptr) is
str : String := Interfaces.C.Strings.Value(s);
begin
Ada.Text_IO.Put_Line(str);
end Print_It;
end Ada_Decs;
main.c:
#include <stdio.h>
extern void ada_print_it (const char *s);
int main(int argc, const char *argv[]) {
const char *hello = "Hello";
ada_print_it(hello);
}
Upvotes: 3
Views: 214
Reputation:
For a main program written in C, you need to allow the Ada RTS to initialise itself before you can use any of its functionality. And shut itself down on exit.
The adainit()
and adafinal()
calls will do this.
extern void adainit (void);
extern void adafinal (void);
int main(int argc, const char *argv[]) {
adainit();
const char *hello = "Hello";
ada_print_it(hello);
adafinal();
}
For a main program written in Ada. this is taken care of automatically by the binder, Gnatbind.
You may also need to add linker arguments to let the linker find these RTS functions : see the Gnat documents (chapter 3.11, Mixed Language interfacing) for more details. There's a worked example at the bottom of this page.
Both links for gcc9.3; other gcc versions may differ a little so check the correct documentation.
Upvotes: 6