【问题标题】:How can a C program call a Perl function?C 程序如何调用 Perl 函数?
【发布时间】:2011-11-28 15:03:43
【问题描述】:

我正在使用 call_pv 从我的 C 程序中调用 perl 子例程。 我有两个问题:

  1. C 程序如何找到该子例程在哪个 Perl 文件中定义?有什么地方可以定义 Perl 文件名吗?

  2. 如果 Perl 返回一个哈希引用作为输出,我如何在 C 中读取它?

这是我的 C 函数:

static int call_perl_fn(char* image)
{

dSP;
int count;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(image, 0))); //parameter to perl subroutine
PUTBACK;
count = call_pv("ImageInfo", G_SCALAR); //Invoking ImageInfo subroutine
SPAGAIN;
if (count != 1)
{
    printf("ERROR in call_pv");
}
printf("VALUE:%s", (char*)(SvRV(POPp))); //How to read has reference output?
PUTBACK;
FREETMPS;
LEAVE;

return count;
}

【问题讨论】:

    标签: c perl


    【解决方案1】:

    使用argv[1] 放置文件名,所以在perl_run(my_perl_interpreter); 之前执行以下操作:

    char *my_argv[] = { "", "NAME_HERE.pl" };
    perl_parse(my_perl_interpreter, NULL, 2, my_argv, (char **)NULL);
    

    关于返回值,应该使用POPs而不是POPp来获取一个SV值,然后通过SvTYPE()检查它以确定类型,并进行相应的处理。

    看看http://perldoc.perl.org/perlembed.htmlhttp://perldoc.perl.org/perlcall.html

    【讨论】:

    • ... 和 "perlapi" 提供有关宏和函数的文档,这些宏和函数用于处理原生数据类型(如 SV*、AV*、HV* 和朋友)的 perl 的 C 表示。
    【解决方案2】:

    1) call_pv 与 Perl 中的 ImageInfo($image) 相比,在文件中找不到 subs。您需要像往常一样创建潜艇。

    2) 参考什么?例如对字符串的引用:

    SV * rv;
    SV * sv;
    char * buf;
    STRLEN len;
    
    rv = POPs;
    if (!SvROK(rv)) {
       ... error ...
    }
    
    sv = SvRV(rv);
    buf = SvPVutf8(sv, len);  # For text. Use SvPVbyte for strings of bytes.
    ...
    

    对哈希的引用更像是:

    SV * rv;
    SV * sv;
    HV * hv;
    
    rv = POPs;
    if (!SvROK(rv)) {
       ... error ...
    }
    
    sv = SvRV(rv);
    if (SvTYPE(sv) != SVt_PVHV) {
       ... error ...
    }
    
    hv = MUTABLE_HV(sv);
    ... Use hv_* functions to look into the hash ...
    

    perlapi

    【讨论】:

    • 哈希参考 更新了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多