yinian 发表于 2015-12-27 11:28:31

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.c
ar -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 $VERSION
PREREQ_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 module
AUTHOR => '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 too
MYEXTLIB => '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_test
void
chen(name)
char * name
  红色部分为增加代码
  
  编译并安装,安装需要root 权限



perl Makefile.PL
make
make install
  
  编写一个测试程序two_test.pl, 测试扩展



#!/usr/bin/perl
use two_test;
$one = "sfjak";
&two_test::chen($one);
  
  执行程序



perl two_test.pl
  
  输出:
input string is : sfjak
  成功调用扩展
  
  参考文章:
一个简单例子
http://www.iyunv.com/old_jh/25/951221.html
IBM介绍如何使用c扩展perl
http://www.ibm.com/developerworks/cn/aix/library/0908_tangming_perltoc/
介绍如何使用C++扩展perl
页: [1]
查看完整版本: perl C/C++ 扩展(二)