我在c中編寫了一個(gè)dll庫(kù),使用vs2017 64位編譯,并嘗試使用64位python3.6加載它。但是,對(duì)象的成員變量的地址被截?cái)酁?2位。這是我的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腳本:from ctypes import cdlllib = cdll.LoadLibrary(r'sim.dll')class Detector(object): def __init__(self): self.obj = lib.Detector_new() def process(self,pin, pout, n): lib.Detector_process(self.obj,pin, pout, n)detector = Detector()n = 1024a = np.arange(n, dtype=np.uint32)b = np.zeros(n, dtype=np.int32)aptr = a.ctypes.data_as(ctypes.POINTER(ctypes.c_int))bptr = b.ctypes.data_as(ctypes.POINTER(ctypes.c_int))detector.process(aptr, bptr, n)這是addr_debug.txt中member_var的地址:member_var init address: 0000025259E123C4member_var process address: 0000000059E123C4因此訪問(wèn)它會(huì)觸發(fā)內(nèi)存訪問(wèn)錯(cuò)誤:OSError: exception: access violation reading 0000000059E123C4我試圖了解這個(gè)問(wèn)題的一些嘗試:將member_var定義為public而不是private,而不是幫助,地址仍然被截?cái)唷ember_var定義為全局變量,然后地址就可以了。所以我猜想在將對(duì)象返回到python或?qū)?duì)象傳遞回dll時(shí)會(huì)發(fā)生member_var地址截?cái)唷?
Python ctypes cdll.LoadLibrary,實(shí)例化一個(gè)對(duì)象,執(zhí)行其方法
呼喚遠(yuǎn)方
2019-09-06 16:06:22