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

前端 未结 1 894
孤独总比滥情好
孤独总比滥情好 2021-01-14 03:04

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

相关标签:
1条回答
  • 2021-01-14 03:46

    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)
    
    0 讨论(0)
提交回复
热议问题