Best Practices for passing option hashes into XS
Simon Wistow
simon at thegestalt.org
Sun Apr 28 01:55:21 BST 2013
I have a method
sub foo {
my ($arg1, %opts) = @_;
}
which I want to translate to XS - what's the best practices for this?
Both my C and my XS are incredibly rusty.
My first thought is something like (modulo memory leaks):
In Foo.xs
void
foo(arg1, ...)
char* arg1
PREINIT:
HV* opts = newHV();
CODE:
int count;
for (int count=1; count<items; count+=2) {
hv_store(opts, ST(count), ST(count+1));
}
and then pass the HV into some C code. But I dislike having Perl types
in otherwise Perl free code.
So my second thought is to have a struct
typedef struct {
char* first_opt;
char* second_opt;
} foo_struct;
void
foo(arg1, ...)
char* arg1
CODE:
foo_struct* opts = malloc(sizeof(foo_struct));
opts.first_opt = 0;
opts.second_opt = 0;
opts.third_opt = 0;
for (int count=1; count<items; count+=2) {
if (ST(count) == "first_opt") {
opts.first_opt = ST(count+1);
} elsif (ST(count) == "second_opt") {
opts.second_opt = ST(count+1);
} else {
croak("Unknown option");
}
}
But that seems ugly too. I feel like I can't be the first person to have
done something like this. Any other modules that I can ripoff^W get
inspiration from?
More information about the london.pm
mailing list