python - 使用 CTypes 时检测从 Windows DLL 调用 Python 脚本

标签 python windows dll ctypes

我正在寻求在 Windows dll 中添加功能以检测调用 Python 脚本的名称。

我正在使用 ctypes 通过 Python 调用 dll,如 How can I call a DLL from a scripting language? 的答案中所述

在 dll 中,我能够使用 WINAPI GetModuleFileName() 成功确定调用进程 http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx .但是,由于这是一个 Python 脚本,它通过 Python 可执行文件运行,因此返回的模块文件名为“C:/Python33/Python.exe”。我需要执行调用的实际脚本文件的名称。这可能吗?

关于原因的一些背景知识:此 dll 用于身份验证。它使用共享 key 生成散列,供脚本用于验证 HTTP 请求。它嵌入在 dll 中,因此使用脚本的人不会看到 key 。我们要确保调用脚本的 python 文件已签名,这样不仅任何人都可以使用此 dll 生成签名,因此获取调用脚本的文件路径是第一步。

最佳答案

一般来说,无需使用 Python C-API,您可以获得进程命令行并使用 Win32 将其解析为 argv 数组 GetCommandLineCommandLineToArgvW .然后检查 argv[1] 是否为 .py 文件。

Python 演示,使用 ctypes:

import ctypes
from ctypes import wintypes

GetCommandLine = ctypes.windll.kernel32.GetCommandLineW
GetCommandLine.restype = wintypes.LPWSTR
GetCommandLine.argtypes = []

CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)
CommandLineToArgvW.argtypes = [
    wintypes.LPCWSTR,  # lpCmdLine,
    ctypes.POINTER(ctypes.c_int),  # pNumArgs
]

if __name__ == '__main__':
    cmdline = GetCommandLine()
    argc = ctypes.c_int()
    argv = CommandLineToArgvW(cmdline, ctypes.byref(argc))
    argc = argc.value
    argv = argv[:argc]
    print(argv)

关于python - 使用 CTypes 时检测从 Windows DLL 调用 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673657/

相关文章:

Python 匹配正则表达式总是返回 None

c# - TreeView 随机无法显示新添加的节点

java - 如何使用Java从Windows Vault中检索用户名和密码?

c++ - VS2010 中的不一致链接

dll - 我不断听说 DLL hell ——这是什么?

python - 基于 Python 3.9 的软件无法在 Windows 7 上运行

python - Python按位赋值运算符中的竖线

python - Django Forms - 多对多关系

python - 数据框行迭代期间出错

c - Linux 和 Windows 之间 fwrite 的不同行为