博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Visual studio 2008下用SWIG包裹C/C++代码给Perl调用(Windows XP)
阅读量:4352 次
发布时间:2019-06-07

本文共 2451 字,大约阅读时间需要 8 分钟。

SWIG, Simplified Wrapper and Interface Generator, 简单来说是C/C++语言与其他语言的粘合剂 。

官方站点:

 

介绍在Visual Studio 2008 下面如何用Swig制作DLL给Perl用(最后测试出现错误)。

假如你有一个 example.c 的文件(官方站点上的例子):

 

double Foo = 3.0;

int gcd(int x, int y) {

int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}

想把这个文件给Perl用。

首先用Visual Studio 2008 建一个C++的win32 project工程,点击next后选择

Application type: DLL(选择该项)

Additional options: Empty project(选择该项)

然后finish.

把 example.c 的文件加入工程中source files。

然后写一个接口文件 example.i :

 

%module example

%{
extern int  gcd(int x, int y);
extern double Foo;
%}
extern int  gcd(int x, int y);
extern double Foo;

把这个example.i文件加入工程中。

注意%{ 和 %}之间的文字将原封不动的写入SWIG生成的wrap文件(example_wrap.c),相当于在wrap文件的函数声明。

然后在系统中设置三个环境变量,主要是为了设置编译环境方便。

如果Perl装在C盘。

PERL5_INCLUDE=C:\Perl\lib\CORE      Perl的include文件夹

PERL5_LIB=C:\Perl\lib\CORE\perl514.lib      Perl的静态库文件,可能根据版本不同而不同,我装的是5.14。

SWIG=E:\software\swigwin-2.0.8\swigwin-2.0.8\swig.exe      swig.exe 的路径( 下载SWIG: )。

环境变量设置完后需要重新启动 Visual Studio 2008 才有效。

右击example.i,点击Properties中Custom Build Step

设置Command line:

 

echo In order to function correctly, please ensure the following environment variables are correctly set:

echo PERL5_INCLUDE: %PERL5_INCLUDE%
echo PERL5_LIB: %PERL5_LIB%
echo on
$(SWIG) -perl5 $(InputPath)

和dos命令一样,最后一句相当于

F:\Software\swigwin-2.0.8\swig.exe -perl5 example.i

Outputs设置成$(InputName)_wrap.c 相当于example_wrap.c

然后选择整个工程的Properties的Configuration Properties

设置C/C++中General的Additional Include Directories: $(PERL5_INCLUDE)

设置Linker中Input的Additional Dependencies: $(PERL5_LIB)

然后编译。第一次编译后会生成example.pm,example_wrap.c。把example_wrap.c加入工程,再编译一次就ok了。把DLL拷贝到example.pm的目录里面,用 runme.pl 测试。

 

#

# Perl5 script for testing simple example

use example;

# Call our gcd() function

$x = 42;

$y = 105;
$g = example::gcd($x,$y);
print "The gcd of $x and $y is $g\n";

# Manipulate the Foo global variable

# Output its current value

print "Foo = $example::Foo\n";

# Change its value

$example::Foo = 3.1415926;

# See if the change took effect

print "Foo = $example::Foo\n";

测试结果:

The gcd of 42 and 105 is 21

Foo = 3
Foo = 3.1415926

-----------------------------------------------------------------

最后测试的时候出现以下错误:

F:\>perl runme.pl

Can't locate loadable object for module example in @INC (@INC contains: C:/Perl/site/lib C:/Perl/lib .) at example.pm line 11
Compilation failed in require at runme.pl line 4.
BEGIN failed--compilation aborted at runme.pl line 4.

 

REF:

转载于:https://www.cnblogs.com/emanlee/archive/2012/08/21/2648848.html

你可能感兴趣的文章