从另一个perl模块调用外部内联C块的函数

hiz5n14c  于 8个月前  发布在  Perl
关注(0)|答案(1)|浏览(79)

我正在寻找一种方法来调用一个函数的内联C块目前在一个Perl文件从另一个文件的内联C块。
我有一个perl文件,其中包含内联C块中的get_instrument_price函数

package Dev::Instrument::Price;

use warnings 'all';
use strict;

use Inline C => <<'__END_OF_C__';

int get_instrument_price(int type)
{ return 154; }

__END_OF_C__

还有另一个文件应该调用上述文件以获取仪器价格

package Dev::Instument::Detail;

use warnings 'all';
use strict;

use Inline C => <<'__END_OF_C__';

extern int *get_instrument_price(int type);

int get_instrument_detail(int type)
{ 
    # some code
    int instrument_price = get_instrument_price(type);
    # some more code
}

__END_OF_C__

我试过使用LIBS => '-L/_Inline/lib/auto',就像下面的参考文献中提到的那样,对我不起作用。
引用自:

  1. Calling an external C function (in a shared lib) from Perl with Inline/C does not work
  2. https://www.foo.be/docs/tpj/issues/vol5_3/tpj0503-0005.html
  3. https://metacpan.org/dist/Inline-C/view/lib/Inline/C/Cookbook.pod
kxe2p93d

kxe2p93d1#

一种解决方法是将常见的C函数拆分到一个单独的库中,例如:

libincodile/instrument.c

#include "instrument.h"
int get_instrument_price(int type)
{
    return 154;
}

libincodile/instrument.h

int get_instrument_price(int type);

lib/Dev/Instrument/Detail.pm

package Dev::Instrument::Detail;
use FindBin;
my $lib_dir;
BEGIN {
    $lib_dir = $FindBin::RealBin . '/libinstrument';
}
use warnings 'all';
use strict;
#use Inline Config => build_noisy => 1, clean_after_build => 0, print_info => 1;
use Inline C => config => libs => "-L$lib_dir -linstrument";
use Inline C => config => inc => '-I' . $lib_dir;
use Inline C => <<'__END_OF_C__';

#include "instrument.h"
int get_instrument_detail(int type)
{
    // some code
    int instrument_price = get_instrument_price(type);
    // some more code
    return instrument_price + 1;
}
__END_OF_C__
1;

lib/Dev/Instrument/Price.pm

package Dev::Instrument::Price;
use warnings 'all';
use strict;

use FindBin;
my $lib_dir;
BEGIN {
    $lib_dir = $FindBin::RealBin . '/libinstrument';
}
use Inline C => config => libs => "-L$lib_dir -linstrument";
use Inline C => config => inc => '-I' . $lib_dir;
#use Inline Config => build_noisy => 1, clean_after_build => 0, print_info => 1;
use Inline C => <<'__END_OF_C__';
#include "instrument.h"

int foo(int type)
{
    int instrument_price = get_instrument_price(type);
    return instrument_price + 2;
}
__END_OF_C__
1;

p.pl

#! /usr/bin/env perl
use v5.38;
use lib './lib';
use Dev::Instrument::Price;
use Dev::Instrument::Detail;

say Dev::Instrument::Price::foo(1);
say Dev::Instrument::Detail::get_instrument_detail(1);

编译公共库

$ gcc -shared -fPIC -o libinstrument.so instrument.c

输出

$ perl p.pl
156
155

相关问题