22
33No setuptools, no Cython: one compiler invocation, `-shared -fPIC`, on macOS
44`-undefined dynamic_lookup` (the extension resolves the C API from the process that loads it).
5+ On Windows the compiler is MSVC (`cl /LD`, linked against the interpreter's import library); see
6+ `msvc_command` and `msvc_env`.
57The headers and the extension suffix default to the host interpreter's (`sysconfig`), and can be
68pointed at the CPython the app embeds (`python_include`, `ext_suffix`).
79"""
810from __future__ import annotations
911
1012import importlib .machinery
1113import importlib .util
14+ import os
15+ import platform
16+ import re
1217import shlex
18+ import shutil
1319import subprocess
1420import sys
1521import sysconfig
2632)
2733
2834
35+ # The same intent for cl.exe: /O2; /fp:precise (no fast-math; contraction is off by default);
36+ # /we4013 makes an implicit function declaration an error; _CRT_SECURE_NO_WARNINGS silences the
37+ # C4996 deprecation of getenv and friends; /std:c11 for the C11 the generated code may use.
38+ MSVC_DEFAULT_FLAGS : tuple [str , ...] = (
39+ "/O2" ,
40+ "/fp:precise" ,
41+ "/we4013" ,
42+ "/std:c11" ,
43+ "/D_CRT_SECURE_NO_WARNINGS" ,
44+ )
45+
46+ # Components cl.exe needs from a Visual Studio installation (vswhere -requires).
47+ MSVC_COMPONENT = "Microsoft.VisualStudio.Component.VC.Tools.x86.x64"
48+
49+
2950class CBuildError (RuntimeError ):
3051 """The C compiler rejected the generated source; the message carries its stderr."""
3152
@@ -43,7 +64,148 @@ def _python_include(python_include: Path | None) -> Path:
4364
4465
4566def compiler () -> list [str ]:
46- return shlex .split (sysconfig .get_config_var ("CC" ) or "cc" )
67+ cc = sysconfig .get_config_var ("CC" )
68+ if not cc and sys .platform == "win32" :
69+ return ["cl" ]
70+ return shlex .split (cc or "cc" )
71+
72+
73+ def _is_msvc () -> bool :
74+ """MSVC drives the build on Windows, or wherever the configured compiler is cl.exe."""
75+ if sys .platform == "win32" :
76+ return True
77+ cc = compiler ()
78+ return bool (cc ) and Path (cc [0 ]).stem .lower () == "cl"
79+
80+
81+ def _msvc_flags (flags : list [str ] | tuple [str , ...]) -> list [str ]:
82+ """Translate a GCC-style flag list for cl.exe: `/flag` passes through, `-D`, `-U` and `-I`
83+ become `/D`, `/U` and `/I`, and every other `-flag` is GCC/Clang-only and dropped. The GCC
84+ default list maps to MSVC_DEFAULT_FLAGS."""
85+ if tuple (flags ) == DEFAULT_FLAGS :
86+ return list (MSVC_DEFAULT_FLAGS )
87+ out : list [str ] = []
88+ rest = list (flags )
89+ if tuple (rest [:len (DEFAULT_FLAGS )]) == DEFAULT_FLAGS : # the defaults plus extra flags
90+ out = list (MSVC_DEFAULT_FLAGS )
91+ rest = rest [len (DEFAULT_FLAGS ):]
92+ for f in rest :
93+ if f .startswith ("/" ):
94+ out .append (f )
95+ elif f [:2 ] in ("-D" , "-U" , "-I" ):
96+ out .append ("/" + f [1 :])
97+ return out
98+
99+
100+ def msvc_libs_dir (include : Path ) -> Path :
101+ """The directory with the interpreter's import library (python3NN.lib, python3NNt.lib for the
102+ free-threaded build): `<prefix>\\ libs`. For an include directory of another CPython
103+ (`<root>\\ include`) its sibling `libs` wins."""
104+ sibling = Path (include ).parent / "libs"
105+ if sibling .is_dir ():
106+ return sibling
107+ return Path (sys .base_prefix ) / "libs"
108+
109+
110+ def free_threaded (ext_suffix : str | None = None ) -> bool :
111+ """Whether the target CPython is the free-threaded build: the `t` ABI tag of an explicit
112+ extension suffix (`.cp315t-win_amd64.pyd`), else the host interpreter's `Py_GIL_DISABLED`."""
113+ if ext_suffix :
114+ return re .search (r"\.cp\d+t-" , ext_suffix ) is not None
115+ return bool (sysconfig .get_config_var ("Py_GIL_DISABLED" ))
116+
117+
118+ def msvc_command (cl : str , c_file : Path , so : Path , include : Path , runtime : Path ,
119+ flags : list [str ] | tuple [str , ...] = DEFAULT_FLAGS ,
120+ libs_dir : Path | None = None , gil_disabled : bool | None = None ) -> list [str ]:
121+ """`cl /nologo <flags> /LD /I<include> /I<runtime> <c_file> /Fo<obj> /link /LIBPATH:<libs> /OUT:<so>`.
122+
123+ The object file goes next to the source; `/OUT` names the extension (`<name><EXT_SUFFIX>`,
124+ .pyd on Windows). Pure: no filesystem or process access beyond `libs_dir` when it is None.
125+
126+ On a free-threaded CPython `/DPy_GIL_DISABLED=1` is added: the Windows pyconfig.h does not
127+ define it, and without it `#pragma comment(lib, ...)` auto-links python3NN.lib instead of
128+ python3NNt.lib (LNK1104 on a free-threaded install, which has only the latter).
129+ """
130+ libs = libs_dir if libs_dir is not None else msvc_libs_dir (include )
131+ obj = Path (c_file ).with_suffix (".obj" )
132+ ft = free_threaded () if gil_disabled is None else gil_disabled
133+ gil = ["/DPy_GIL_DISABLED=1" ] if ft else []
134+ return ([cl , "/nologo" ] + _msvc_flags (flags ) + gil
135+ + ["/LD" , f"/I{ include } " , f"/I{ runtime } " , str (c_file ), f"/Fo{ obj } " ,
136+ "/link" , f"/LIBPATH:{ libs } " , f"/OUT:{ so } " ])
137+
138+
139+ _UNSET = object ()
140+ _msvc_env_cache : object = _UNSET
141+
142+
143+ def _vswhere_path () -> Path :
144+ base = os .environ .get ("ProgramFiles(x86)" ) or os .environ .get ("ProgramFiles" ) or r"C:\Program Files (x86)"
145+ return Path (base ) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe"
146+
147+
148+ def parse_env_dump (text : str ) -> dict [str , str ]:
149+ """Parse the `set` output of a vcvars run (`NAME=value` per line; banner lines are skipped)."""
150+ env : dict [str , str ] = {}
151+ for line in text .splitlines ():
152+ name , eq , value = line .partition ("=" )
153+ if eq and name and not name .startswith (("[" , " " )):
154+ env [name ] = value
155+ return env
156+
157+
158+ def _find_vcvars () -> Path :
159+ vswhere = _vswhere_path ()
160+ if not vswhere .is_file ():
161+ raise CBuildError (
162+ "MSVC not found: cl.exe is not on PATH and vswhere.exe is missing "
163+ f"({ vswhere } ). Install Visual Studio or the Build Tools with the 'Desktop development "
164+ f"with C++' workload ({ MSVC_COMPONENT } ), or run from a 'x64 Native Tools' prompt." )
165+ run = subprocess .run (
166+ [str (vswhere ), "-latest" , "-products" , "*" , "-requires" , MSVC_COMPONENT ,
167+ "-property" , "installationPath" ], capture_output = True , text = True )
168+ root = run .stdout .strip ().splitlines ()[0 ].strip () if run .returncode == 0 and run .stdout .strip () else ""
169+ if not root :
170+ raise CBuildError (
171+ f"MSVC not found: vswhere.exe found no Visual Studio installation with { MSVC_COMPONENT } "
172+ "(install the 'Desktop development with C++' workload)." )
173+ script = "vcvarsarm64.bat" if platform .machine ().lower () in ("arm64" , "aarch64" ) else "vcvars64.bat"
174+ vcvars = Path (root ) / "VC" / "Auxiliary" / "Build" / script
175+ if not vcvars .is_file ():
176+ raise CBuildError (f"MSVC not found: { vcvars } does not exist (Visual Studio at { root } )." )
177+ return vcvars
178+
179+
180+ def msvc_env () -> dict [str , str ] | None :
181+ """The environment to run cl.exe in; None when cl.exe is already on PATH (use the current one).
182+
183+ Otherwise: vswhere.exe locates the newest Visual Studio with the C++ tools, vcvars64.bat is run
184+ and the environment it leaves is captured. Cached per process.
185+ """
186+ global _msvc_env_cache
187+ if _msvc_env_cache is not _UNSET :
188+ return _msvc_env_cache # type: ignore[return-value]
189+ if shutil .which ("cl" ):
190+ _msvc_env_cache = None
191+ return None
192+ vcvars = _find_vcvars ()
193+ env = dict (os .environ , VSCMD_SKIP_SENDTELEMETRY = "1" )
194+ run = subprocess .run (f'cmd /u /c "{ vcvars } " && set' , capture_output = True , env = env )
195+ out = run .stdout .decode ("utf-16-le" , errors = "replace" )
196+ captured = parse_env_dump (out )
197+ if run .returncode != 0 or not any (k .upper () == "INCLUDE" for k in captured ):
198+ raise CBuildError (f"{ vcvars } failed ({ run .returncode } ) or did not set INCLUDE:\n { out [- 2000 :]} " )
199+ _msvc_env_cache = captured
200+ return captured
201+
202+
203+ def _msvc_cl (env : dict [str , str ] | None ) -> str :
204+ cl = shutil .which ("cl" , path = None if env is None else next (
205+ (v for k , v in env .items () if k .upper () == "PATH" ), None ))
206+ if not cl :
207+ raise CBuildError ("MSVC not found: cl.exe is not on PATH (after vcvars)" )
208+ return cl
47209
48210
49211def build (c_source : str , module_name : str , out_dir : Path , runtime_dir : Path | None = None ,
@@ -63,6 +225,16 @@ def build(c_source: str, module_name: str, out_dir: Path, runtime_dir: Path | No
63225 c_file = out_dir / f"{ stem } .c"
64226 c_file .write_text (c_source , encoding = "utf-8" )
65227 so = out_dir / f"{ stem } { suffix } "
228+ if _is_msvc ():
229+ env = msvc_env ()
230+ cmd = msvc_command (_msvc_cl (env ), c_file , so , include , runtime , flags ,
231+ gil_disabled = free_threaded (ext_suffix ))
232+ run = subprocess .run (cmd , capture_output = True , text = True , env = env )
233+ if run .returncode != 0 or not so .is_file ():
234+ # cl.exe reports its errors on stdout
235+ raise CBuildError (f"C compiler failed ({ run .returncode } ): { subprocess .list2cmdline (cmd )} \n "
236+ f"{ run .stdout } { run .stderr } " )
237+ return so
66238 cmd = compiler () + list (flags ) + ["-fPIC" , "-shared" , f"-I{ include } " , f"-I{ runtime } " ]
67239 if sys .platform == "darwin" :
68240 cmd += ["-undefined" , "dynamic_lookup" ]
0 commit comments