2

I'm trying, using the Inline::CPP module, to pass two pointers as arguments to a C function but I get the error No typemap for type int *. Skipping void swapPointer(int *, int *) and I can't figure out what I have to do to achieve my goal. I would like some help, please.

This is my code:

#!/usr/bin/perl

use Inline CPP;

my $x = 1 ;
my $y = 2 ;

swapPointer(\$x, \$y); 
 
print "X:$x Y:$y" ; # expected: $x => 2 and $y => 1

__END__
__CPP__
   
void swapPointer(int* a, int* b)
{
  int tmp = *a;
  *a = *b;
  *b = tmp;
}
Hannibal
  • 445
  • 4
  • 13
  • 1
    Try use `SV *` instead of `int *` ? See [this](https://stackoverflow.com/a/18293582/2173773) answer – Håkon Hægland Apr 03 '22 at 14:36
  • 1
    Great! I tried to use `SV*` and that solved the `typemap` issue. I'm now able to get the ref content (just a pointer) using the `SvRV(SV*)` macro. – Hannibal Apr 03 '22 at 17:24

1 Answers1

3

You could try use SV * instead of int *, see this answer for more information. Her is an example:

Here is an example:

use feature qw(say);
use strict;
use warnings;
use Inline 'CPP';

my $x = 1 ;
my $y = 2 ;

swapPointer(\$x, \$y);

say "X:$x Y:$y" ; # expected: $x => 2 and $y => 1

__END__
__CPP__

void swapPointer(SV* rva, SV* rvb)
{
  if (!SvROK(rva)) croak( "first input argument is not a reference" );
  if (!SvROK(rvb)) croak( "second input argument is not a reference" );
  SV *sva = (SV *)SvRV(rva);
  SV *svb = (SV *)SvRV(rvb);
  if (SvROK(sva)) croak( "first input argument is a reference to a reference" );
  if (SvROK(svb)) croak( "second input argument is a reference to a reference" );
  if ( SvTYPE(sva) >= SVt_PVAV ) croak( "first input param is not a scalar reference" );
  if ( SvTYPE(svb) >= SVt_PVAV ) croak( "second input param is not a scalar reference" );
  SV *temp = newSVsv(sva);
  sv_setsv(sva, svb);
  sv_setsv(svb, temp);
  SvREFCNT_dec(temp);  // Free the temporary SV
}

Output:

X:2 Y:1
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • Thanks Håkon Hægland for suggesting me to use the `SV*` and above all for the complete and working example !! You saved my day :-) !!! – Hannibal Apr 03 '22 at 17:30
  • @Hannibal Great! I fixed a small bug in the code I posted first, please check latest version – Håkon Hægland Apr 03 '22 at 17:49
  • Why do you forbid swapping scalars that contain references? `SvTYPE(sva) >= SVt_PVAV` is also incorrect as it prevents swapping IO objects. – ikegami Apr 03 '22 at 18:32
  • @ikegami *"Why do you forbid swapping scalars that contain references?"* No particular reason, except the OP's code start with assuming ints. So they can decide if they will except other objects as well. I do not know what they intended in the first place.. – Håkon Hægland Apr 03 '22 at 18:42