简体   繁体   中英

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.

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()

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