Python3でctypesを使ってWindowsの特殊フォルダを開く関数のコードとそれを書く過程で学んだことです。
フォントフォルダを開く
import os
import ctypes
from ctypes import oledll, wintypes
def getshellfolderpath(csidl: int) -> str:
if not isinstance(csidl, int):
raise TypeError
SHGetFolderPathW = oledll.shell32.SHGetFolderPathW
SHGetFolderPathW.argtypes = [
wintypes.HWND, ctypes.c_int, wintypes.HANDLE,
wintypes.DWORD, wintypes.LPWSTR]
path = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
SHGetFolderPathW(0, csidl, 0, 0, path)
return path.value
CSIDL_FONTS = 0x0014
os.startfile(getshellfolderpath(CSIDL_FONTS))
- Python 3では標準ライブラリのctypesを使ってWin32 APIを操作できる。
- Win32 APIの一般的な型(
HWND、DWORD等)はctypes.wintypesに定義されている。 -
ctypesは動的リンクライブラリのロードのためにcdll、pydll、windll、oledllをエクスポートする。cdll、pydllはcdecl呼び出し規約、windllとctypes.oledllはstdcall呼び出し規約。ctypes.oledllは戻り値をHRESULTと仮定して失敗時にOSErrorを送出する。公式ドキュメント。 -
WCHAR型のバッファーはctypes.create_unicode_buffer関数で作成する。戻り値のvalueで文字列を取得できる。公式ドキュメント。 - ファイル/フォルダを関連付けで開くには
os.startfile関数が使える。