named arguments to XS function?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

hi there,

i'm wondering if it's possible to pass named arguments to an XS
function like so:

$myObj = Package::Bla->new(arg1=>"hello", arg2=>"world");

in XS i'm not sure what to ask for on the argument list. if i just take
an HV*, it doesn't work, an SV* also doesn't work. any ideas?

Gabe Schine

Re: named arguments to XS function?

Quoted text here. Click to load it

If you pass those arguments to new(), it will be receiving a list of the 4
strings "arg1", "hello", "arg2", "world" - in that order.

You can have new receive those 4 args as either  'char*' or 'SV*'. In either
case perl's typemaps will handle them correctly for you.

If you want to deal with the 'HV*' then the function needs to be passed a
reference to a hash. (Similarly, if the function returns a HV*, it's
returning a reference to a hash.)

The following Inline::C scripts demonstrates those points:

use warnings;

use Inline C => Config =>
    BUILD_NOISY => 1;

use Inline C => <<'EOC';

void foo1 (SV * key1, SV * val1, SV * key2, SV * val2) {
     printf("%s %s %s %s\n", SvPV_nolen(key1), SvPV_nolen(val1),
                             SvPV_nolen(key2), SvPV_nolen(val2));

void foo2 (char * key1, char * val1, char * key2, char * val2) {
     printf("%s %s %s %s\n", key1, val1, key2, val2);

HV * foo3 (HV * x) {
     return x;


$hashref = {(arg1 => 'hello', arg2 => 'world')};

foo1(arg1 => 'hello', arg2 => 'world');
foo2(arg1 => 'hello', arg2 => 'world');

$copy = foo3($hashref);

print $copy->, " ", $copy->, "\n";



Re: named arguments to XS function?


worked like a charm. makes a lot of sense, too, knowing how perl does

Site Timeline