I am trying to invoke some C++ functions in Python code with Python ctypes. I have two code files: one is core_lib.cpp, which defines a class and a member method; the other is demo.py, which instantiates the class and calls the member method.
core_lib.cpp is defined as below.
#include <iostream>
#include <tuple>
using namespace std;
class A {
private:
string _name;
tuple<int, int> _size;
public:
A() {
this->_name = "";
this->_size = make_tuple(1, 1);
cout << "Init values of _size: " << get<0>(this->_size) << ", " << get<1>(this->_size) << endl;
}
void set_size(int* size) {
int a = *size;
int b = *(size+1);
this->_size = make_tuple(a, b);
cout << "New values of _size: " << get<0>(this->_size) << ", " << get<1>(this->_size) << endl;
}
};
// bridge C++ to C
extern "C" {
A* create_A() {
return new A();
}
void set_size(A* a, int* size) {
a->set_size(size);
}
}
demo.py is defined as below.
from ctypes import *
import os
# load C++ lib
core_lib = cdll.LoadLibrary(os.path.abspath('test/stackoverflow/core_lib.so'))
class A(object):
def __init__(self):
self.a = core_lib.create_A()
def set_size(self, size):
core_lib.set_size(self.a, size)
if __name__ == "__main__":
asize = (3, 3)
size = (c_int * 2)(*asize)
a = A()
a.set_size(size)
To reproduce the issue, I list my steps here:
- Compile core_lib.cpp: g++ core_lib.cpp -fPIC -shared -std=c++11 -o core_lib.so
- Run the python script: python demo.py
The Python version is 2.7.15, and runs on MacOS Mojave.
According to my investigation, the issue is caused by the code line in core_lib.cpp:
this->_size = make_tuple(a, b)
I tried to google the issue, but I didn't find an answer. I would appreciate any comment that would help understand the issue and how to fix it.