How to use C++ dll in python

I have a library with functions and structures written in C++. It can also be used in C# using a wrapper in a cs-file, which describes C# interfaces that call functions from a DLL. That is, to use the C# API, you only need a DLL file. How can I do the same for python? In addition to the DLL, I also have the .h file, but not the .cpp file.

Upvotes: 4

Views: 2083

Answers (1)

Lars Kakavandi-Nielsen
Lars Kakavandi-Nielsen

Reputation: 2198

You will need to use ctypes and you have to have an intermediate layer of C.

Let us say we have a file called duck.cpp

#include <iostream>

class Duck 
{
public: 
    void quack() {std::cout << "Quck\n";}
};

extern "C" {
  Duck* New_Duck(){return new Duck();}
  void Duck_Quack(Duck* duck) {duck->quack();}
}

The compiled, here with G++, I will generate an .so and not a dll as I am on Linux:

g++ -c -fPICK duck.cpp -o duck.o
g++ -shared -Vl,-soname,libduck.so -o libduck.so duck.o

Then in Python

from ctypes import cdll

lib = cdll.LoadLibrary('./libduck.so')

class Duck(object): 
    def __init__(self):
        self.obj = lib.New_Duck()

    def quak(self): 
        lib.quck(self.obj)

if __name__ == "__main__":
    duck = Duck()
    duck.quack()

Upvotes: 1

Related Questions