Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^3: Can't create XSUBs for C functions with a same name

by davido (Archbishop)
on Aug 23, 2012 at 16:02 UTC ( #989342=note: print w/ replies, xml ) Need Help??


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

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


Comment on Re^3: Can't create XSUBs for C functions with a same name
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://989342]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2014-09-21 14:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (172 votes), past polls