首页 > 代码库 > perl C/C++ 扩展(二)
perl C/C++ 扩展(二)
第二讲
perl 加载c/c++的库
先通过h2xs 创建一个新的工程
h2xs -A -n two_test
进入目录
cd two_test
创建一个mylib文件夹,存放静态库
mkdir mylib
c程序头文件chen.h
#include<stdio.h>void chen(char *);
c程序代码chen.c
#include "chen.h"void chen(char * name){printf("input string is : %s\n", name);}
编译静态库
gcc -c chen.car -r libchen.a chen.o
将libchen.a静态库与chen.h头文件拷贝到two_test/mylib
cp libchen.a two_test/mylib/cp chen.h two_test/mylib
修改perl 生成makefile 的脚本Makefile.PL
use 5.014002;use ExtUtils::MakeMaker;# See lib/ExtUtils/MakeMaker.pm for details of how to influence# the contents of the Makefile that is written.WriteMakefile(NAME => ‘two_test‘,VERSION_FROM => ‘lib/two_test.pm‘, # finds $VERSIONPREREQ_PM => {}, # e.g., Module::Name => 1.1($] >= 5.005 ? ## Add these new keywords supported since 5.005(ABSTRACT_FROM => ‘lib/two_test.pm‘, # retrieve abstract from moduleAUTHOR => ‘root <root@>‘) : ()),LIBS => [‘‘], # e.g., ‘-lm‘DEFINE => ‘‘, # e.g., ‘-DHAVE_SOMETHING‘INC => ‘-I.‘, # e.g., ‘-I. -I/usr/include/other‘# Un-comment this if you add C files to link with later:# OBJECT => ‘$(O_FILES)‘, # link all the C files tooMYEXTLIB => ‘mylib/libchen.a‘);
MYEXTLIB => ‘mylib/libchen.a‘ 是新增的命令,作用是在生成perl 扩展包时包含libchen.a的库
修改two_test.xs 文件
#include "EXTERN.h"#include "perl.h"#include "XSUB.h"#include "ppport.h"#include "mylib/chen.h"MODULE = two_test PACKAGE = two_testvoidchen(name)char * name
红色部分为增加代码
编译并安装,安装需要root 权限
perl Makefile.PLmakemake install
编写一个测试程序two_test.pl, 测试扩展
#!/usr/bin/perluse two_test;$one = "sfjak";&two_test::chen($one);
执行程序
perl two_test.pl
输出:
input string is : sfjak
成功调用扩展
参考文章:
一个简单例子
http://www.chinaunix.net/old_jh/25/951221.html
IBM介绍如何使用c扩展perl
http://www.ibm.com/developerworks/cn/aix/library/0908_tangming_perltoc/
介绍如何使用C++扩展perl
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。