我正在寻求在 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
数组 GetCommandLine和 CommandLineToArgvW .然后检查 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/