python - ctypes,python3.5,OSError : exception: access violation writing 0x00000000

标签 python python-3.x ctypes python-3.5

研究其他类似的错误,我认为我有一个非法操作的问题,例如写入一个我不应该的地址。我不确定如何解决这个问题。有什么帮助吗?

我得到的确切错误:

in GetSoftwareVersion()
result = f(LCP_Version, FCP_Version)
OSError: exception: access violation writing 0x00000000 

我正在调用的函数

x = GetSoftWareVersion()
print(x)

GetSoftwareVersion() 内容

def GetSoftwareVersion():
    f = shim.GetSoftwareVersion

    LCP_Version = ct.c_char_p(0)
    FCP_Version = ct.c_char_p(0)

    result = f(LCP_Version, FCP_Version)

    if result:
        print(find_shim_error(result))

    return LCP_Version.contents.value, FCP_Version.contents.value

编辑:添加相关的C++代码

PCSHIMDLL_API  error_status_type GetSoftwareVersion(
        char* LCP_Version,
        char* FCP_Version
        )
{
    error_status_type return_status = SUCCESS;
    string LCP_V("");
    string FCP_V("");
    LaserIDType_var laserID;
    laserID = p_DiagIF->GetLaserID();
    LCP_V = laserID->m_LCPSoftwareVersion;
    FCP_V = laserID->m_FCPSoftwareVersion;
    strcpy(LCP_Version, LCP_V.c_str());
    strcpy(FCP_Version, FCP_V.c_str());

    return return_status;
}

最佳答案

由于语句 LCP_Version = ct.c_char_p(0),您收到错误 OSError: exception: access violation writing 0x00000000。正如 ctypes documentation for c_char_p 所建议的那样你正在传递一个整数地址。

你告诉 ctypes 要做的是创建一个指向 0 的新 char *,然后尝试 strcpy 通过 strcpy(LCP_Version, LCP_V.c_str());。如果你要使用 ct.c_char_p(1),你会得到 访问冲突写入 0x0000001,如果 c_char_p(2),则在0x...2,依此类推。您的内存不太可能允许您写入该位置,因此出现错误。

您可能想要做的是使用 create_string_buffer(N) ,其中 N 是包含 LCP_V = laserID->m_LCPSoftwareVersion; 输出所需的数组大小。 create_string_buffer,顾名思义,将为您提供一个初始化为空字节的可变字符缓冲区(例如,p = create_string_buffer(3) 表示 p大小为 3,内容为 b'\x00\x00\x00)。您可以猜测并检查或查看 p_DiagIF->GetLaserID(); 的源代码以寻找 N 的安全值,或者只是给自己一些巨大的东西(对于版本号)像 LCP_Version = ct.c_char_p(50) 并从那里选择一些正常的东西。

关于python - ctypes,python3.5,OSError : exception: access violation writing 0x00000000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37973033/

相关文章:

python - Python ImageIO 中动画 Gif 的自定义帧持续时间

python - 如何只打印一个txt文件中的一行? (Python)

python - 使用 ctypes 返回值

python - 压缩迭代器和计数迭代器的乘积

python - 将 Qt 类型与 ctypes 和 python 一起使用

python - 在从另一个用 C 实现的类驱动的类上使用元类

python - Bokeh 热图的使用

python - 我是否能够将变量分离到另一个类中但保持用法相同?

python - 设置包含 1 个列表和列表列表的字典

python - 在 python 中使用正则表达式操作解析出 URL