perl - Inline::CPP - 如何将指针 (int*) 作为 C 函数的参数处理

标签 perl

我正在尝试使用 Inline::CPP 模块将两个指针作为参数传递给 C 函数,但出现错误 No typemap for type int *。跳过 void swapPointer(int *, int *) 我不知道我必须做什么才能实现我的目标。 我需要一些帮助,请。

这是我的代码:

#!/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;
}

最佳答案

您可以尝试使用 SV * 而不是 int *,请参阅 this回答以获取更多信息。她就是一个例子:

这是一个例子:

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
}

输出:

X:2 Y:1

关于perl - Inline::CPP - 如何将指针 (int*) 作为 C 函数的参数处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71725738/

相关文章:

perl - 使用 Perl 将一个散列插入另一个散列

linux - 为什么我在执行 1 个 fork 时会得到 2 个进程?

perl - 在 Perl 中通过 SMTP 发送邮件

perl - 如何使用 Perl 检查文件是否打开?

regex - 如何使用 Shell 或 Perl 替换字符串,即使它包含正则表达式元字符?

regex - Perl 替换嵌套 block 正则表达式

Perl,在 x 秒后使脚本超时?

regex - 使用 grep 查找匹配的字符串不会返回匹配的值

perl - 这个表达能起作用吗?

javascript - 单击按钮调用 Perl 函数并将返回值填充到表单中的文本字段中