使用XS在perl上暴露c函数



我在这个格式上有多个c函数:

int function(const char* input, size_t len, char result[]) ;

其中int为返回类型;

result[]包含函数填充的字符串

如何编写XS这样的函数并将其暴露在perl中:

  1. 获取函数的返回值

  2. 在perl上获取char结果[]值

我尝试了下面的操作,但下面只返回返回值

int
my_function(a,b,c)
    const char *  a
    long            b
    const char *    c
    CODE:
    RETVAL =function(a,b,c)
    OUTPUT:
    RETVAL

新建目录,复制以下文件:

。/Example.xs

#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "ppport.h"    
#include "const-c.inc"
int my_function(const char* input, size_t len, char result[])
{
    strcpy(result, "the answer");
    return 42;
}
MODULE = Acme::XS::Example        PACKAGE = Acme::XS::Example
INCLUDE: const-xs.inc
PROTOTYPES: DISABLE
void
my_xsub (input, len)
    char *input
    int len
PPCODE:
{
    char result[10];
    int got = my_function(input, len, result);
    /* create a new scalar from an int, and push onto stack */
    PUSHs( newSViv(got) );
    /* create a new scalar from a string, and push onto stack */
    PUSHs( newSVpv(result, 0) );
    XSRETURN(2);  /* two items returned */
}

。/lib/Acme/XS/Example.pm

use 5.010001;
use strict;
use warnings;
use XSLoader ();
package Acme::XS::Example;
our $VERSION   = '0.001';
__PACKAGE__->XSLoader::load($VERSION);
1;

。/t/basic.t

use strict;
use warnings;
use Test::More;
use_ok('Acme::XS::Example');
my @results = Acme::XS::Example::my_xsub("Hello world", 666);
is_deeply(
    @results,
    [ 42, "the answer" ],
    "got expected results",
) or diag explain(@results);
done_testing;

。/makefile . pl

use strict;
use Devel::PPPort;
use ExtUtils::MakeMaker 6.6303;
use ExtUtils::Constant;
Devel::PPPort::WriteFile();
ExtUtils::Constant::WriteConstants(
    NAME         => 'Acme::XS::Example',
    NAMES        => [],
    DEFAULT_TYPE => 'IV',
    C_FILE       => 'const-c.inc',
    XS_FILE      => 'const-xs.inc',
);
WriteMakefile(
    NAME       => 'Acme::XS::Example',
    DISTNAME   => 'Acme-XS-Example',
    VERSION    => '0.001',
    ABSTRACT   => 'an example XS thingy',
    AUTHOR     => ['Toby Inkster <tobyink@cpan.org>'],
    LICENSE    => 'perl_5',
    MIN_PERL_VERSION  => '5.010001',
    PREREQ_PM  => {
        'XSLoader'             => 0,
    },
    TEST_REQUIRES => {
        'Test::More'           => '0.96',
    },
    CONFIGURE_REQUIRES => {
        'Devel::PPPort'        => 0,
        'ExtUtils::Constant'   => 0,
        'ExtUtils::MakeMaker'  => '6.6303',
    },
    LIBS       => [''],
    DEFINE     => '',
    INC        => '-I.',
    test       => { TESTS => "t/*.t" },
    clean      => { FILES => 'const-c.inc const-xs.inc ppport.h' },
);

这是你要玩的骨架。: -)

构建和测试它:

perl Makefile.PL
make
make test

程序h2xs可用于创建perl/XS模块,该模块充当C代码的包装器。我想你会想要创建一个头文件,里面有你的函数原型。

请参阅h2xs的手册页了解详细信息。另外,看一下这里

perl函数(也是XS函数)可以返回多个值。
您需要使用PPCODE而不是CODE,并将多个变量作为结果压入堆栈。查看perlxs文档中的PPCODE示例

相关内容

  • 没有找到相关文章

最新更新