怎樣從perl中調(diào)用c庫里的函數(shù)
發(fā)布時間:2008-08-06 閱讀數(shù): 次 來源:網(wǎng)樂原科技
假如你所用的庫是mylib.a 頭文件是mylib.h
假如mylib.h像以下內(nèi)容:
extern void hello();
hello()函數(shù)假如執(zhí)行如下功能:
void hello()
{
printf("Success call from perl to c libray!\n";
}
一、建立工作目錄mytest,把mylib.a和mylib.h放到mytest中
二、在mytest的上層目錄執(zhí)行
h2xs -O -n mytest ./mytest/mylib.h
三、進(jìn)入mytest,修改mytest.xs,在文件末尾增加perl接口
void
hello()
CODE:
hello();
改變#include <./mytest/mylib.h>
為 #include "mylib.h"
一般情況下此行都需要修改。
四、修改Makefile.PL,其中#add begin和#add end中間的內(nèi)容是新增加的。
use ExtUtils::MakeMaker;
# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.
WriteMakefile(
'NAME' => 'mytest',
'VERSION_FROM' => 'mytest.pm', # finds $VERSION
'LIBS' => [''], # e.g., '-lm'
'DEFINE' => '', # e.g., '-DHAVE_SOMETHING'
'INC' => '', # e.g., '-I/usr/include/other'
#add begin
'MYEXTLIB' => 'mylib.a',
#add end
);
#add begin
sub MY::postamble()
{
'
$(MYEXTLIB): .
';
#add end
}
五、執(zhí)行perl Makefile.PL,讓perl生成makefile
六、執(zhí)行make
七、修改測試文件test.pl,修改完畢后改變?yōu)榭蓤?zhí)行
#!/usr/bin/perl
# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl test.pl'
######################### We start with some black magic to print on failure.
# Change 1..1 below to 1..last_test_to_print .
# (It may become useful if the test is moved to ./t subdirectory.)
use ExtUtils::testlib;
BEGIN { $| = 1; print "1..1\n"; }
END {print "not ok 1\n" unless $loaded;}
use mytest;
$loaded = 1;
print "ok 1\n";
######################### End of black magic.
# Insert your test code below (better if it prints "ok 13"
# (correspondingly "not ok 13") depending on the success of chunk 13
# of the test code):
mytest::hello();
八、此時你應(yīng)該能夠看到
Success call from perl to c libray!