好的,这是一个非常有趣的问题,并且可能没有任何简单的方法可以做到这一点但是我想在我决定修改Perl是我的基本答案之前将其抛弃。
所以我有一个以嵌入式方式调用Perl脚本的C应用程序。这一切都很好,花花公子,我可以传递信息并获取信息非常棒。然而,现在进入我的下一次征服;我需要允许我的嵌入式脚本能够在C应用程序中调用一些原本调用它的函数。
这很重要,因为XSUB会要求它是一个外部库;但我不希望它是一个外部库我希望它是对C函数的直接调用。现在也许这可以通过XSUB完成,我刚刚阅读并理解错误。
Application -(run)-> Perl
Application <-(function_x())- Perl
Application -(returnfunction_x)-> Perl
这不能是外部库的原因是因为我依赖的是仅在应用程序中创建/存储的数据。
答案 0 :(得分:7)
XSUB实际上不需要有外部库。它们只提供从perl空间调用c函数的能力,并为映射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函数中完成此类操作。
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可以自由地以任何方式回复您的应用程序。