使用CType时从Windows DLL检测调用Python脚本

我正在寻求在Windows dll中添加功能以检测调用Python脚本的名称.我正在使用ctypes通过Python调用dll,如How can I call a DLL from a scripting language?的答案中所述在dll中,我能够使用WINAPI GetModuleFileName(...

我正在寻求在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.可执行程序”.我需要执行该调用的实际脚本文件的名称.这可能吗?

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

解决方法:

通常,无需使用Python C-API,就可以使用Win32 GetCommandLine和CommandLineToArgvW获取进程命令行并将其解析为argv数组.然后检查argv [1]是否为.py文件.

使用ctypes的Python演示:

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)

本文标题为:使用CType时从Windows DLL检测调用Python脚本

基础教程推荐