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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With