在Ada中访问C字符串时出现分段错误
我试图从Ada子程序访问C程序中声明的字符串,但遇到了一个分段错误。有人能帮我解决这个问题吗 下面是一个失败的例子,似乎segfault来自ada_decs.adb中对在Ada中访问C字符串时出现分段错误,c,segmentation-fault,ada,C,Segmentation Fault,Ada,我试图从Ada子程序访问C程序中声明的字符串,但遇到了一个分段错误。有人能帮我解决这个问题吗 下面是一个失败的例子,似乎segfault来自ada_decs.adb中对Interfaces.C.Strings.Value的调用,但我不确定为什么,或者我如何才能使它工作 gdb的回溯显示: #0 0x00000000004167ea in system.secondary_stack.ss_mark () #1 0x00000000004037e6 in ada_print_it (s=0x4
Interfaces.C.Strings.Value
的调用,但我不确定为什么,或者我如何才能使它工作
gdb的回溯显示:
#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
(用(…)
表示完整的文件路径)
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;
主要条款c:
#包括
外部无效数据打印(const char*s);
int main(int argc,const char*argv[]{
const char*hello=“hello”;
ada_print_it(你好);
}
对于用C编写的主程序,您需要允许Ada RTS进行自身初始化,然后才能使用其任何功能。在出口处自动关闭
adainit()
和adafinal()
调用将执行此操作
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();
}
对于用Ada编写的主程序。这由活页夹Gnatbind自动处理 您可能还需要添加链接器参数,以便链接器找到这些RTS函数:有关更多详细信息,请参阅(第3.11章,混合语言接口)。有一个成功的例子
gcc9.3的两个链接;其他gcc版本可能会有一些不同,所以请检查正确的文档。
chars\u ptr
对应于char*
,而不是const char*
,尽管这在这里不太可能是个问题。我也这么认为,所以我尝试了这两种方法,但在我的情况下没有什么不同。太好了,这对我来说很有效。不需要链接器参数,只需将它们声明为extern
。非常感谢。