Perl的:我怎样才能把我所有的联C code到一个单独的文件? [英] Perl: how can I put all my inline C code into a separate file?
问题描述
这问题是如此简单,我可以感觉到RTFM的到来。不过,我一直在寻找的文档(在线,的内嵌-C ,的内嵌-C-食谱)整个上午,我无法弄清楚如何解决这个问题。
This problem is so simple I can feel the RTFM's coming. However, I've been looking at the docs (Inline, Inline-C, Inline-C-Cookbook ) all morning and I can't figure out how to solve this problem.
我要使用内联C,但我不希望有C code。在相同的文件中我的Perl code。
I want to use inline C, but I don't want to have C code in the same file as my perl code.
(Emacs的不喜欢在一个文件中有两种语言。原则上,这是一个方便的事情,但在实践中我在编辑我的C在一个文件然后将其复制并粘贴到我的Perl脚本。)
(Emacs doesn't like having two languages in one file. In principle this is a matter of convenience, but in practice I'm having to edit my C in one file then copy-paste it into my perl script.)
下面是工作的Perl:
Here is working perl:
#!/usr/bin/perl
use Inline C => DATA;
use strict;
use warnings;
use List::Util qw(sum);
use feature qw(say);
my @array = (1..10);
say "native perl: ", sum(@array), ", Inline C: ", sum1(\@array);
__END__
__C__
double sum1(AV* array) {
int i;
double sum = 0.0;
for (i=0; i<=av_len(array); i++) {
SV** elem = av_fetch(array, i, 0);
if (elem != NULL)
sum += SvNV(*elem);
}
return sum;
}
(感谢<一个href=\"http://stackoverflow.com/questions/1503763/how-can-i-pass-an-array-to-a-c-function-in-perl-xs\">mobrule你为我这么远。)
欲所有的C $ C $的c(或尽可能)移到单独的头文件。
I want to move all of the C code (or as much as possible) into a separate header file.
什么我能做的就是把 SUM1
进入标题,做到这一点:
What I can do is put sum1
into a header, and do this:
# same perl as above except now say sum2 instead of sum1
__END__
__C__
#include "sum.h"
double sum2(AV* array) {
sum1(array);
}
这是不够好,因为我再也不用编辑在Perl模式的C,但我不知道如果没有一个更优雅的解决这个问题?
This is good enough as I no longer have to edit the C in perl-mode, but I wonder if there isn't a more elegant solution to this problem?
推荐答案
您可以把你的C code在一个单独的文件,并使用内嵌::绑定
来在运行时加载它
You can put your C code in a separate file and use Inline::bind
to load it at runtime
use Inline;
use File::Slurp;
my $data = read_file('source.c');
Inline->bind(C => $data);
或加载在 BEGIN {}
块在编译时绑定源$ C $ C
or loading the source code in a BEGIN {}
block to bind it at compile time
my $data;
use File::Slurp;
BEGIN {
$data = read_file('source.c');
}
use Inline C => $data;
这篇关于Perl的:我怎样才能把我所有的联C code到一个单独的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!