Skip to content
This repository was archived by the owner on Nov 14, 2022. It is now read-only.
This repository was archived by the owner on Nov 14, 2022. It is now read-only.

64 位 Python + 64 位库并不能将目前的 Demo 跑起来(无法直接迁移使用 64 位) #3

Description

@ynyyn

背景

在本 Demo 在诞生之时及随后较长的一段时间内,Miniblink 都仅官方支持 32 位,也就是仅发布 32 位动态链接库,任何 64 位程序都无法直接加载使用,这也意味着只有使用 32 位 Python 才能运行本 Demo。

虽然没有官方发布的 x64 版,但非官方的 x64 编译版还是有的。

因此笔者在当时也做过使用 64 位库的技术验证。接下来将介绍的内容,也正是当时所得到的。但是由于当时无官方 x64 版,所以未公开相关技术内容和调整。

但是由于近期 Miniblink 增加了官方 x64 版本的支持,故现在有必要将该问题拿出来进行简单的说明。

64 位 Python + 64 位库并不能将目前的 Demo 跑起来(无法直接迁移使用 64 位)

受制于 ctypes 库的一些固有特性,目前本 Demo 需要略作修改才能切换到 64 位使用,无法直接迁移运行,即便使用 64 位的 Python 和配套的 64 位的动态链接库(miniblink_x64.dll)。

具体技术原因

ctypes 库对于任何未指定返回值类型(restype)的函数调用,默认认为其返回的是 int 类型

By default functions are assumed to return the C int type.

然而 64 位库函数的指针类型为 64 位。当 64 位指针返回时,如若先前未告知 ctytes 返回类型,则ctypes 遵循上面的默认规则,视作 int 类型,导致返回到 Python 侧的是 32 位截断值。

事实上,不仅返回值有该特性,参数值也有类似的特性。如使用 ctypes 调用库函数时未指定参数类型,当传入 Python 原生的 integer 类型时,会截断成 C 的 int 类型后传入。

Python integers are passed as the platforms default C int type, their value is masked to fit into the C type.

说了这么多,在本 Demo 中的一种反映就是:Miniblink 创建的 webview 很不巧地就是指针类型,而本 Demo 也很不巧地(作为一个很粗糙的原型)没有在使用 ctypes 函数调用前预先指定被调函数的参数列表和返回值。

        mb = ctypes.cdll.LoadLibrary("miniblink_x64.dll")
        webview = mb.wkeCreateWebWindow(
            0, # WKE_WINDOW_TYPE_POPUP
            None, 0, 0,
            1024, 768 # width, height
        )
        mb.wkeMoveToCenter(webview)

所以在 64 位 Miniblink 下,webview 的返回值被截断,在 Python 侧得到的 webview 值并不正确,并且后续调用中把错误的 webview 传给库函数,库函数引用了错误的内存而导致内存非法访问错误。

这就是目前 Demo 代码无法直接迁移到 64 位运行的最主要原因。欲修复该问题,需要预先为库函数指定参数和返回值类型(至少为不得不指定类型的函数指定)。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingenhancementNew feature or request

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions