在嵌入式C应用程序中从Perl调用C函数

好吧,这是一个非常有趣的问题,并且可能没有任何简单的方法可以做到这一点,但想到我会在决定修改Perl是我的基本答案之前抛弃它。

所以我有一个以嵌入式方式调用Perl脚本的C应用程序。 这一切都很好,花花公子,我可以传递信息并获取信息非常棒。 但是,现在进入我的下一次征服; 我需要允许我的嵌入式脚本能够调用原始C叫它的C应用程序中的一些函数。

这很重要,因为XSUB会要求它是一个外部库; 但我不希望它成为一个外部库我希望它是对C函数的直接调用。 现在也许这可以通过XSUB完成,我刚刚阅读并理解错误。

Application -(run)-> Perl Application  Perl 

这不能是外部库的原因是因为我依赖于仅在应用程序中创建/存储的数据。

XSUB实际上不需要有外部库。 它们只提供从perl空间调用ac函数的能力,并为映射C和Perl之间的调用约定提供了一些便利。

您需要做的就是将您编译的XSUB注册到嵌入式应用程序中,并使用您正在嵌入的perl解释器。

 #include "XSUB.h" XS(XS_some_func); XS(XS_some_func) { dXSARGS; char *str_from_perl, *str_from_c; /* get SV*s from the stack usign ST(x) and friends, do stuff to them */ str_from_perl = SvPV_nolen(ST(0)); /* do your c thing calling back to your application, or whatever */ str_from_c = some_c_func(str_from_perl); /* pack up the c retval into an sv again and return it on the stack */ mXPUSHp(c_str); XSRETURN(1); } /* register the above XSUB with the perl interpreter after creating it */ newXS("Some::Perl::function", XS_some_func, __FILE__); 

嵌入perl时,这种事情通常在传递给parse_perl的xs_init函数中parse_perl

 EXTERN_C void boot_DynaLoader (pTHX_ CV* cv); static void xs_init (pTHX) { newXS("Some::Perl::function", XS_some_func, __FILE__); /* possibly also boot DynaLoader and friends. perlembed has more * details on this, and ExtUtils::Embed helps as well. */ newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); } perl_parse(my_perl, xs_init, argc, my_argv, NULL); 

之后,您将能够从perl空间调用XSUB作为Some::Perl::function ,并且XSUB可以以任何方式自由地回调您的应用程序。