Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access global perl variables from inline C

Tags:

perl

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
like image 284
packetie Avatar asked Nov 23 '16 14:11

packetie


1 Answers

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);
    const char *val = SvPVutf8_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 */
    const char *val = SvPVutf8_nolen(var);
    printf("Value of $Foo::Bar is %s", val);
}

This is documented in perlguts.

like image 163
mob Avatar answered Oct 16 '22 21:10

mob