简体   繁体   English

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

[英]Creating a C++ Wrapper in Python using .dylib

I'm basically trying to develop a Wrapper in Python that can access a library I have developed in C++. 我基本上是在尝试使用Python开发一个Wrapper,该Wrapper可以访问我在C ++中开发的库。 At the minute, it is very basic, as this is just for testing purposes. 目前,这是非常基本的,因为这只是出于测试目的。

In my .h file I have the following: 在我的.h文件中,我具有以下内容:

#include <iostream>

class Foo {

  public:

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

And in my Python file I call using the following: 在我的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()

I have created a .dylib since I don't believe it is possible to create a shared library in GCC on a mac, but, I could be wrong. 我创建了.dylib,因为我不相信可以在Mac上的GCC中创建共享库,但是,我可能是错的。 I'm getting the following errors: 我收到以下错误:

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

But it is found, and the library (.dylib) is infact in the same directory.. Where am I going wrong? 但是找到了,并且库(.dylib)实际上在同一目录中。

The ctypes library doesn't know about c++, you need to write your shared library in c if you want to use ctypes . ctypes库不了解c ++,如果要使用ctypes则需要使用c编写共享库。

You can look at something like http://www.swig.org instead, which can hook into a shared library written in c++. 您可以查看类似http://www.swig.org的内容 ,它可以连接到用c ++编写的共享库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM