4

从 Perl 调用 C 函数时,例如使用Inline::C

use feature qw(say);
use strict;
use warnings;
use Inline C => './test.c';

say "Calling test()..";
test();
say "Finished.";

哪里test.c是:

void test() 
{
    SV *sv_variable = newSVpv("test", 0);

    // do something..

    //SvREFCNT_dec(sv_variable); // free variable
    printf( "Returning from test()..\n");
    return;

}

无论我是否打电话,该脚本似乎都可以正常工作SvREFCNT_dec(sv_variable)。根据perlguts

要释放您创建的 SV,请调用 SvREFCNT_dec(SV*)。通常不需要这个调用

4

1 回答 1

4

是的,您应该减少引用计数。(如果不这样做,则不会立即产生不良影响,但是您已经造成了内存泄漏。)

perlguts 可能会说这通常是不必要的,因为大多数 SV 不仅仅在 C 函数内部使用;它们是可从 Perl 空间访问或放入堆栈的结构的一部分。

But note that your code structure isn't exception safe: If any function in // do something throws, sv_variable will leak (because SvREFCNT_dec is never reached). This can be fixed by doing:

SV *sv_variable = sv_2mortal(newSVpv("test", 0));

sv_2mortal is like a deferred SvREFCNT_dec: It will decrement the reference count some time "later".

(If you're creating an SV from a string literal, newSVpvs("test") is better than newSVpv because it doesn't have to compute the length at runtime.)

于 2017-02-25T12:49:36.843 回答