SWIG:仅使用 header 和共享库为 Perl 包装 C++,无法定位可加载的 object 错误

SWIG: Wrapping C++ for Perl using only a header and a shared library, can't locate loadable object error

我正在尝试学习 SWIG,但在让 SWIG 在 Linux 机器上使用 perl 时遇到了一些问题。我有文件 Dog.h、Crow.h、Animal.i 和 libmylib.so。所有这些文件都在同一个目录中。 libmylib.so 是使用 Dog.cpp 和 Crow.cpp 编译的,它们分别引用 Dog.h 和 Crow.h。我的Animal.i文件如下:

%module Animal
%{
/* Includes the header in the wrapper code */
#include "Dog.h"
#include "Crow.h"
%}

/*Parse the header file to generate wrappers */
%include "Dog.h"
%include "Crow.h"

以下是我为构建 perl 模块而执行的命令:

swig -perl -c++ Animal.i
g++ -shared -fPIC Animal_wrap.cxx -L. -lmylib -I/usr/lib64/perl5/CORE -o _Animal.so
LD_LIBRARY_PATH=. perl

当我键入 "use Animal;" 时,出现以下错误:"Can't locate loadable object for module Animal in @INC"。我是 perl 的新手,所以我不确定如何解决这个问题,尽管通过四处搜索我觉得问题可能是 perl 无法引用我的 libmylib.so 文件。任何帮助将不胜感激。谢谢!

以下似乎适用于 Ubuntu 16.04:

文件:

Animal.i:

%module Animal
%{
#include "Dog.h"
#include "Crow.h"
%}
%include "Dog.h"
%include "Crow.h"

Crow.h

class Crow {
public:
    Crow()  {
        ncrows++;
    }
    virtual ~Crow() {
        ncrows--;
    }
    static  int ncrows;
};

Dog.h:

class Dog {
public:
    Dog()  {
        ndogs++;
    }
    virtual ~Dog() {
        ndogs--;
    }
    static  int ndogs;
};

Crow.cpp:

#include "Crow.h"
int Crow::ncrows = 0;

Dog.cpp:

#include "Dog.h"
int Dog::ndogs = 0;

test.pl:

use strict;
use warnings;
use Animal;

print "Creating a Crow:\n";
my $c = Animal::Crow->new();
print "    Created crow $c\n";
$c->DESTROY();
print "Creating a Dog:\n";
my $d = Animal::Dog->new();
print "    Created dog $d\n";
$d->DESTROY();

编译:

swig -perl -c++ Animal.i
g++ -fPIC -c Crow.cpp
g++ -fPIC -c Dog.cpp
g++ -shared Crow.o Dog.o -o libmylib.so
g++ -fPIC -c Animal_wrap.cxx -I/usr/lib/x86_64-linux-gnu/perl/5.22/CORE
g++ -shared -L. Animal_wrap.o -lmylib -o Animal.so

运行 测试脚本:

$ LD_LIBRARY_PATH=. perl test.pl 
Creating a Crow:
    Created crow Animal::Crow=HASH(0x10c2eb0)
Creating a Dog:
    Created dog Animal::Dog=HASH(0x10c2f88)