powerman has asked for the wisdom of the Perl Monks concerning the following question:

I've C library with function expecting char* param which must be NULL in some cases. I wish to use it from perl this way:
c_func(undef); # NULL param c_func(''); # empty string param c_func(123); # string '123' param c_func('qwe'); # string 'qwe' param

Current XS realization:

void c_func(param) char * param = SvOK(ST(0)) ? SvPV_nolen(ST(0)) : NULL;

This task sounds like standard opration, so is there exists simpler way, without ugly "SvOK ? SvPV_nolen : NULL" chain?

Replies are listed 'Best First'.
Re: XS: SvOK ? SvPV_nolen : NULL
by creamygoodness (Curate) on Jun 08, 2006 at 15:12 UTC

    Provided that you don't want to be warned when the argument is undef, your code is correct.

    --
    Marvin Humphrey
    Rectangular Research ― http://www.rectangular.com
Re: XS: SvOK ? SvPV_nolen : NULL
by wazzuteke (Hermit) on Jun 08, 2006 at 19:38 UTC
    If you are trying to ditch the SvOK(SV*) ternary, you could add extra validation on the Perl side before calling c_func

    For example:
    # Assuming this is within the *.pm package, and you are # only allowing a single parameter # as (what looks to be) defined in your XS c_func( ( ( defined( $_[0] ) ) ? $_[0] : '' ) );
    Where you can implicitly force the SvOK check in Perl-land. Though, this would simply move the ternary into Perl rather than in the XS; maybe what you are looking for.

    Hope that helps!

    print map{chr}(45,45,104,97,124,124,116,97,45,45);
    ... and I probably posted this while I was at work => whitepages.com | inc.