0

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?

1
  • The library (or one of its dependencies) could not be found. Try os.path.isfile('./libfoo.1.dylib') first. Commented Feb 21, 2018 at 8:09

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, got it! But, what if the library is hosted on a server - Is this possible?
What do you mean? Give an example. There are many ways to do RPC (Remote Procedure calls) and one comes built-in with python, docs.python.org/2/library/xmlrpclib.html and all of them means that you need a server-client kind of setup
Anderrsson - Thanks for the reply. Basically, I'm doing raspberry pi but it can't handle the requests that I have (in C++) so I have placed the library onto an external server and I just want to create a wrapper that interacts with this. My main concern is that in C++ I use std::vector and obviously, in python there is no such thing... Are there ways to get around such?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.