我试图用Python cType调用Python代码中的一些C++函数。我有两个代码文件:一个是core-lib.cpp,它定义了一个类和一个成员方法;另一个是demo.py,它实例化了类并调用了成员方法。
核心方案
定义如下。
#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);
}
}
演示.py
定义如下。
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)
为了重现这个问题,我在这里列出了我的步骤:
-
编译core-lib.cpp:
G+ + CIEE.LIP.CPP-FPIC-共享STD=C++ 11 -O CORE
-
运行python脚本:
python演示.py
python版本是2.7.15,运行在macos mojave上。
根据我的调查,这个问题是由core-lib.cpp中的代码行引起的:
this->_size = make_tuple(a, b)
我试图在谷歌上搜索这个问题,但没有找到答案。我希望任何有助于理解这个问题以及如何解决它的评论。