Skip to content

Instantly share code, notes, and snippets.

@genio

genio/test.xs Secret

Last active July 22, 2017 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genio/a8020a64fae04879e90d7d33d53871ce to your computer and use it in GitHub Desktop.
Save genio/a8020a64fae04879e90d7d33d53871ce to your computer and use it in GitHub Desktop.
An XS constructor taking either a hash or hash ref
SV * some_constructor_new(SV *class, ...)
CODE:
{
int iStack;
SV *temp;
SV **val;
HV *params;
PERL_UNUSED_VAR(class);
if (items < 2) {
/* Nothing was provided, construct an empty hash for parameters */
params = (HV *)sv_2mortal((SV *)newHV());
}
if (items == 2) {
/* only one item was supplied, let's see if it was a hash ref */
temp = newSVsv(ST(1));
if (SvROK(temp) && SvTYPE(SvRV(temp)) == SVt_PVHV) {
params = (HV *)SvRV(temp);
}
else {
croak("Expected a hash reference or a hash of parameters to new");
}
}
else if (items > 2 && (items-1) % 2 == 0) {
/* we have many things, but an even number of them, let's assume key, value pairs */
params = (HV *)sv_2mortal((SV *)newHV());
for (iStack = 1; iStack < items; iStack += 2) {
hv_store_ent(params, ST(iStack), newSVsv(ST(iStack+1)), 0);
}
}
else {
/* we have no idea what the user gave us. DIE */
croak("Expected a hash reference or a hash of parameters to new");
}
/* dump the hash params to ensure we have what we thought we should */
sv_dump((SV *)params);
/* check if a hash param exists! */
if (hv_exists(params, "int_val", 4)) {
/* get the value if it does exist */
val = hv_fetchs(params, "int_val", NULL);
/* do something with that value */
}
/* return our hash ref to Perl to see what we should do with it there. */
/* we'd normally make our object from the data in the hash ref here and return that */
/* but this is just for my own memory of how to do all of the above */
RETVAL = newRV_inc((SV*)params);
}
OUTPUT:
RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment