我正在寻求在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脚本


基础教程推荐
- python-如何在Windows上以提升的特权运行脚本? 2023-11-11
- centos7 下安装 python3.6.4 安装virtualenv 来隔离python2 和python3 的环境 2023-09-03
- 如何在Ubuntu 12.04上从源代码为python2.6编译pygtk 2023-11-13
- Python sklearn库三种常用编码格式实例 2022-10-20
- osx中的rsvg python内存泄漏(ctypes?) 2023-11-12
- Python中非常好用的内置函数详解 2023-08-04
- python-为什么在Linux环境中使用pyodbc插入空值? 2023-11-12
- Python+Opencv实现物体尺寸测量的方法详解 2022-10-20
- python的环境conda简介 2022-10-20
- python中线程 进程 协程 2023-11-11