Recent C++/SWIG stories
muppet
scott at asofyet.org
Thu Sep 28 01:33:48 BST 2006
On Sep 27, 2006, at 8:33 AM, Toby Corkindale wrote:
> On Wed, Sep 20, 2006 at 02:23:13PM +0100, Simon Wistow wrote:
>> On Wed, Sep 20, 2006 at 09:31:50AM +0100, Nigel Rantor said:
>>>
>>> Anyone tried wrapping clean, recent C++ code in Perl using SWIG?
>>
>> No, but I've written XS by bhand for C++.
>>
>> It was pretty easy.
>
> Can you apply C++'s function overloading to deal with varying
> arguments from
> Perl?
> eg:
> int foo::bar(int val) {
> RETVAL = val + 13;
> }
> int foo::bar(string word) {
> RETVAL = word.append("13");
> }
Sure, but it's not automatic. After all, the C++ compiler chooses
which overloaded signature to use compile time, and perl decides that
at runtime, so you have to have code in place to deal with each
one. There are variations; choose as appropriate based on the
complexity of your argument handling:
a) Bind a different version of the function for each signature.
Then, in perl code, parse your arguments and call the correct
implementation.
In the .pm:
sub bar {
my $self = shift;
my $arg = shift;
if ($arg =~ /^\s*\d+\s*$/) { # looks like a number
$self->_bar_i ($arg);
} else {
$self->_bar_s ($arg);
}
}
In the .xs:
void _bar_i (int i)
CODE:
THIS->bar (i);
void _bar_s (const char *s)
CODE:
THIS->bar (s);
b) Do something like that, but all in XS:
void bar (SV *arg)
CODE:
if (looks_like_number (arg)) {
THIS->bar (SvIV (arg));
} else {
THIS->bar (SvPV_nolen (arg));
}
(looks_like_number() is a very handy C function from embed.h
(macro) / proto.h (prototype).)
--
Fun park. Fun swings. Fun play Zaz. I like dinosaurs.
- Yvonne, aged two and a half, recounting the events of the day at
bedtime.
More information about the london.pm
mailing list