C++ code:
#include <iostream>
class DemoClass{
private:
int a, b;
public:
DemoClass(int v1, int v2){
a = v1;
b = v2;
}
void DemoFunction(){
std::cout << "Hello C++!" << std::endl;
std::cout << "output: a = " << a << ", b = " << b << std::endl;
}
};
extern "C" {
DemoClass* DemoCpp(int v1, int v2){
return new DemoClass(v1, v2);
}
void DemoCppFunction(DemoClass* demo){
demo->DemoFunction();
}
}
compile c++ via g++ test.cpp -shared -fPIC -o test.so
Python script:
from ctypes import cdll
lib = cdll.LoadLibrary('./test.so')
class CppClass():
def __init__(self, v1: int, v2: int):
self.obj = lib.DemoCpp(v1, v2)
def demoFunction(self):
lib.DemoCppFunction(self.obj)
f = CppClass(2, 3)
f.demoFunction()
Here is what I get:
Hello C++!
Segmentation fault
I am pretty sure the parameters are passed to C++ class. I just want to know a way to call the function in a C++ class.