in reply to Re: Can't create XSUBs for C functions with a same name
in thread Can't create XSUBs for C functions with a same name

Thanks for the idea, Rob. Indeed, I have a C++ code. Sorry about confusion. Here is what I came up with after all:
int add(...) CODE: if (items == 2) RETVAL = add((int)SvIV(ST(0)), (int)SvIV(ST(1))); else RETVAL = add((int)SvIV(ST(0)), (int)SvIV(ST(1)), (int)SvIV(ST(2))) +; OUTPUT: RETVAL
Although, I was hoping there was some XS trick to handle this situation in a more elegant way.

Replies are listed 'Best First'.
Re^3: Can't create XSUBs for C functions with a same name
by davido (Cardinal) on Aug 23, 2012 at 16:02 UTC

    For what it's worth, Rob's code is also valid for C++ (and Inline::CPP):

    use strict; use warnings; use Inline CPP => Config => BUILD_NOISY => 1; use Inline CPP => <<'EOCPP'; int add(SV * a, ...) { dXSARGS; int i, ret = 0; for(i = 0; i < items; i++) ret += SvIV(ST(i)); return ret; } EOCPP print add(11, 12), "\n"; # prints 23 print add(10, 11, 12), "\n"; # prints 33

    ...outputs...

    23 33

    While that's still not the same as function overloading, It's actually one of the best (clearest) examples I've seen anywhere on how to use the "..." parameter. I might have to add it to Inline::CPP's POD on some future release.

    Another approach would be to use Inline::CPP, and wrap your functions in classes:

    use strict; use warnings; use Inline CPP => Config => BUILD_NOISY => 1; use Inline CPP => 'DATA'; my $foo = Foo->new(); my $bar = Bar->new(); sub add { if( @_ == 2 ) { return $foo->add(@_); } return $bar->add(@_); } __DATA__ __CPP__ struct Foo { add( int a, int b ) { return a + b; } }; struct Bar { add( int a, int b, int c ) { return a + b + c } };

    Of course with this process you're adding an additional Perl layer, so if your C++ subs are trivial, your performance will actually go down.

    As the POD for Inline::CPP states, the module enables a large subset of C++, but not all of C++. Function overloading is one of those "not all" areas.


    Dave

Re^3: Can't create XSUBs for C functions with a same name
by Anonymous Monk on Aug 23, 2012 at 11:06 UTC
    Hmm, Wx created macros like MATCH_REDISP to manage dispatch based on args ... not sure if you consider that elegant. There is also ExtUtils::XSpp but its more of the same (and it doesn't include MATCH_REDISP)