SWIG和C ++共享库 [英] SWIG and C++ shared library

查看:51
本文介绍了SWIG和C ++共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++库(我们称其为 mylib ),可以编译为/usr/local/lib 中的 libmylib.so 文件,然后我在/usr/local/include 中名为 my lib 的目录中有一堆头文件.

I have a C++ library (let's call it mylib) which compiles to libmylib.so file in /usr/local/lib and I have a bunch of header files in a directory called my lib in /usr/local/include.

现在,我想做的(对于初学者而言)只是将其中一个头文件(包含有关我的图书馆提供的类的信息)与SWIG一起使用,以生成 mylib_wrap.cxx 文件然后将其编译并链接到现有的 mylib.so .这样我就可以在Python中实例化我的类.

Now the thing I wanted to do (for starters) is just use one of the header files (it contains information about a class my library is offering) with SWIG to generate the mylib_wrap.cxx file and then compile it and link it against the existing mylib.so. So that I can instance my class in Python.

这是正确的方法/想法吗?编译和链接命令的外观如何(当然不完全是)?我正在尝试生成Python绑定.

Is this the right approach/idea? How would the compile and linking command look like (not exactly of course)? I am trying to generate a Python binding.

推荐答案

我为您整理了一个完整的示例:

I've put together a complete example for you:

(mylib.h)

class Foo {
};

void bar(const Foo&);

实施:

#include "mylib.h"
#include <iostream>

void bar(const Foo& f) {
  std::cout << &f << std::endl;
}

编译库:


g++ -fPIC -Wall -Wextra -shared mylib.cc -o libmylib.so

用于包装库的SWIG接口:

%module mylib

// Make mylib_wrap.cxx include this header:
%{
#include "mylib.h"
%}

// Make SWIG look into this header:
%include "mylib.h"

编译Python模块:


swig -Wall -c++ -python mylib.i  
g++ -fPIC -Wall -Wextra -shared mylib_wrap.cxx -o _mylib.so -L. -lmylib -I/usr/include/python2.7/ -lpython2.7 

请注意,我们将Python模块链接到了库.如果它不在当前目录中,则需要指定库路径.SWIG希望Python模块的本机部分称为_module.so

Note that we linked the Python module against the library. If it wasn't in the current directory you'd need to specify the library path. SWIG expects the native part of Python module to be called _module.so


LD_LIBRARY_PATH=. python                                                 
Python 2.7.2+ (default, Nov 30 2011, 19:22:03) 
[GCC 4.6.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mylib
>>> i=mylib.Foo()
>>> mylib.bar(i)
0x28cc100
>>> mylib.bar(i)
0x28cc100
>>> mylib.bar(mylib.Foo())
0x28b3b10

在这里,通过适当设置LD_LIBRARY_PATH,确保我们刚刚构建的共享库位于库路径上.

Here I made sure the shared objects we just built are on the library path by setting LD_LIBRARY_PATH appropriately.

这篇关于SWIG和C ++共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆