packetie packetie - 13 days ago 10
Perl Question

access global perl variables from inline C

I am trying to access perl global variable ($data in this case) from within a inline C function, but the "data" variable I used is not defined.
Any idea how to do it?

Thanks

The following code snippet will give error complaining that the variable "data" is not declared.

$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

mob mob
Answer

Use the get_sv (or get_av / get_hv) macro to access a global variable in Inline/XS code.

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

The GV_ADD flag will create the variable (and initialize it to undef) if it doesn't already exist. If you access a variable that does not already exist and you do not use this flag, get_sv will return NULL.

If the variable you are looking for is in a different package from main, you must qualify it in the get_sv call:

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

This is documented in perlguts.