Access global perl variables from embedded C

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

thanks

The following code fragment will give an error message indicating 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 
+7
perl
source share
1 answer

Use the get_sv macro (or get_av / get_hv ) to access the 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 a variable (and initialize it to undef ) if it does not already exist. If you are accessing a variable that does not yet exist, and you are not using this flag, get_sv will return NULL .

If the variable you are looking for is in another package from main , you should get it in a 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 described in perlguts .

+5
source share

All Articles