简体   繁体   中英

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++. At the minute, it is very basic, as this is just for testing purposes.

In my .h file I have the following:

#include <iostream>

class Foo {

  public:

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

And in my Python file I call using the following:

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. 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?

The ctypes library doesn't know about c++, you need to write your shared library in c if you want to use ctypes .

You can look at something like http://www.swig.org instead, which can hook into a shared library written in c++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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