Combine python (gui) and C++
I have a program that works with files, everything is ready except for the interface, I could easily finish it in C++, but the time is running out. Is it possible to make an interface in Python, and functions in C++? Well, somehow from Python to call them?
1
Author: Victor VosMottor, 2020-11-02
1 answers
Let's say you have a simple example of a C ++ class that you want to call from python, in a file named foo.cpp:
#include <iostream>
class Foo{
public:
void bar(){
std::cout << "Hello" << std::endl;
}
};
Since ctypes can only interact with C functions, you need to provide those that declare them as extern "C"
:
extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(); }
}
Now compile this into a library:
g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
And finally, you need to write your shell(for example, in fooWrapper.py):
from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')
class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()
def bar(self):
lib.Foo_bar(self.obj)
Now everything works ;)
f = Foo()
f.bar() # and you will see "Hello" on the screen
5
Author: Victor VosMottor, 2020-11-02 10:45:28