使用.dylib在Python中创建C ++包装器

时间:2013-09-24 20:57:10

标签: c++ python macos wrapper

我基本上是在尝试用Python开发一个Wrapper,它可以访问我用C ++开发的库。在某一刻,它是非常基本的,因为这仅用于测试目的。

在我的.h文件中,我有以下内容:

#include <iostream>

class Foo {

  public:

    void bar() {
        std::cout << "Hello world";
    }
};

在我的Python文件中,我使用以下内容调用:

from ctypes import cdll 

lib = cdll.LoadLibary('./libfoo.1.dylib')

class Foo(object):
def __init__(self):
    self.obj = lib.Foo_new();

def bar(self):
    lib.Foo_bar(self.obj)

f = Foo();
f.bar();

我创建了一个.dylib,因为我不相信可以在Mac上的GCC中创建共享库,但是,我可能是错的。我收到以下错误:

Traceback (most recent call last):
File "main.py", line 3, in <module>
lib = cdll.LoadLibary('./libfoo.1.dylib')
File     
 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py",   
line 423, in __getattr__
dll = self._dlltype(name)
File
 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py",
line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(LoadLibary, 6): image not found

但是找到它,并且库(.dylib)实际上在同一个目录中..我哪里出错了?

1 个答案:

答案 0 :(得分:1)

ctypes库不了解c ++,如果要使用ctypes,则需要在c中编写共享库。

您可以查看类似http://www.swig.org的内容,它可以挂钩到用c ++编写的共享库中。