在我的cpp文件中
extern "C" {
Password obj;
_declspec(dllexport) BOOL decrypt(const char *encryptedPassword, char *password, size_t *sizeOfThePasswordPtr)
{
return obj.decrypt(encryptedPassword, password, sizeOfThePasswordPtr);
}
}
在我的python文件中:
lib = ctypes.WinDLL(os.path.join(baseDir, "basicLib.dll"))
encryptedValue = ctypes.c_char_p('absfdxfd')
decryptedValue = ctypes.c_char_p()
size = ctypes.c_size_t(1024)
lib.decrypt.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t]
lib.decrypt(encryptedValue, decryptedValue, size)
调用函数时出现此错误WindowsError: exception: access violation reading 0x0000000000000400
。问题是因为encryptedValue
参数。
只有在设置encryptedValue = ctypes.c_char_p()
时它才有效,但如果我传入一些值,我会得到异常。请告诉我原因。
答案 0 :(得分:0)
# WinDLL is for __stdcall functions. Use CDLL.
# This is most likely the cause of your exception because the parameters
# are marshalled on the stack incorrectly.
lib = ctypes.CDLL(os.path.join(baseDir, "basicLib.dll"))
# No need to explicitly create c_char_p objects if you declare argtypes,
# but make sure it is a byte string if using Python 3
encryptedValue = b'absfdxfd'
# Create a writable buffer for the output.
decryptedValue = ctypes.create_string_buffer(1024)
# Good
lib.decrypt.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t]
# No need to declare explicit c_size_t() object either.
lib.decrypt(encryptedValue, decryptedValue, len(decryptedValue))