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

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

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

我得到的确切错误:

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(LCP_Version, LCP_V.c_str()); strcpy 指向它.如果你要使用 ct.c_char_p(1),你会得到 access violation writing 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) 然后选择一些东西从那里理智。