【问题标题】:Ctypes: WindowsError: exception: access violation reading 0x0000000000000400 when calling C++ functionCtypes:WindowsError:异常:调用C++函数时读取0x0000000000000400的访问冲突
【发布时间】:2017-02-15 19:19:30
【问题描述】:

在我的 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() 时才有效,但如果我传入一些值,我会得到异常。请让我知道为什么。

【问题讨论】:

  • 您似乎没有分配任何内存来保存解密后的值。
  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。

标签: python c++ ctypes


【解决方案1】:
# 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))

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2014-11-01
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    相关资源
    最近更新 更多