从内联C访问全局perl变量

时间:2016-11-23 14:38:07

标签: perl

我试图从内联C函数中访问perl全局变量(在这种情况下为$ data),但是"数据"我使用的变量没有定义。 知道怎么做吗?

由于

以下代码段会给出错误抱怨变量" data"没有宣布。

$data = "this is a test";
test();

use Inline C => <<'END_OF_C_CODE';

void test() {
    printf("here: %s\n", SvPV(data, PL_na));
}

END_OF_C_CODE

1 个答案:

答案 0 :(得分:5)

使用get_sv(或get_av / get_hv)宏访问Inline / XS代码中的全局变量。

package main;
use Inline C;
our $Bar = 123;
test();
__DATA__
__C__
void test() {
    SV* var = get_sv("Bar", GV_ADD);
    const char *val = SvPVutf8_nolen(var);
    printf("Value of $Bar is %s", val);
}

GV_ADD标志将创建变量(并将其初始化为undef),如果它尚未存在的话。如果您访问的数据尚不存在且未使用此标记,则get_sv将返回NULL

如果您要查找的变量与main不同,则必须在get_sv来电中对其进行限定:

package Foo;
use Inline C;
our $Bar = 123;
test();
__DATA__
__C__
void test() {
    SV* var = get_sv("Foo::Bar", GV_ADD);   /* need "Foo::" now */
    const char *val = SvPVutf8_nolen(var);
    printf("Value of $Foo::Bar is %s", val);
}

perlguts中记录了这一点。

相关问题