我用c编写了一个dll库,用vs2017 64位编译,并尝试用python3.6 64位加载它。但是,对象的成员变量的地址被截断为32位。在
这是我的sim.c文件,它被编译成sim.dll卡公司名称:
class Detector {
public:
Detector();
void process(int* pin, int* pout, int n);
private:
int member_var;
};
Detector::Detector()
{
memset(&member_var, 0, sizeof(member_var));
myfile.open("addr_debug.txt");
myfile << "member_var init address: " << &member_var << endl;
}
void Detector::process(int* pin, int* pout, int n);
{
myfile << "member_var process address: " << &member_var << endl;
myfile.close();
}
#define DllExport __declspec( dllexport )
extern "C" {
DllExport Detector* Detector_new() { return new Detector(); }
DllExport void Detector_process(Detector* det, int* pin, int* pout, int n)
{
det->process(pin, pout, n);
}
}
下面是我的python脚本:
^{pr2}$这是地址中成员的地址_调试.txt公司名称:
member_var init address: 0000025259E123C4
member_var process address: 0000000059E123C4
因此访问它会触发内存访问错误:
OSError: exception: access violation reading 0000000059E123C4
我试图理解这个问题:
始终(正确)为C中定义的函数指定argtypes和restype,否则(C89样式)将默认为int(通常32bit),生成!!!未定义的行为!!!。在64位上,地址(大于2 GiB)将被截断(这正是您所经历的)。
同一错误的另一个后果是:[SO]: python ctypes issue on different OSes (@CristiFati's answer)。在
另外,遇到问题时,不要忘记[Python 3.Docs]: ctypes - A foreign function library for Python。在
下面是代码的改编版本。在
探测器.cpp:
代码.py:
^{pr2}$注意事项:
detector_new_func.restype = c_void_p
,您将再次遇到问题)new Detector()
)也必须被释放(否则,它将生成一个内存泄漏),因此我添加了一个函数(DetectorDelete),它是从(Python)Detector的析构函数调用的输出:
相关问题 更多 >
编程相关推荐