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

随声附和 提交于 2019-12-19 08:52:08

问题


I'm trying to learn SWIG and I'm having some issues getting SWIG to work with perl on a Linux machine. I have the files Dog.h, Crow.h, Animal.i, and libmylib.so. All these files are in the same directory. libmylib.so was compiled using Dog.cpp and Crow.cpp, which reference Dog.h and Crow.h respectively. My Animal.i file is as follows:

%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"

Here are the commands that I'm executing in order to build the perl module:

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

When I type "use Animal;", I get the following error: "Can't locate loadable object for module Animal in @INC". I'm fairly new to perl so I'm not sure how to go about fixing the issue, although from searching around I feel like the problem might be that perl cannot reference my libmylib.so file. Any help would be greatly appreciated. Thank you!


回答1:


The following seems to work on Ubuntu 16.04:

Files:

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();

Compilation:

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

Running test script:

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


来源:https://stackoverflow.com/questions/38214651/swig-wrapping-c-for-perl-using-only-a-header-and-a-shared-library-cant-loca

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!