extbuild.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """
  2. Build a c-extension module on-the-fly in tests.
  3. See build_and_import_extensions for usage hints
  4. """
  5. import os
  6. import pathlib
  7. import subprocess
  8. import sys
  9. import sysconfig
  10. import textwrap
  11. __all__ = ['build_and_import_extension', 'compile_extension_module']
  12. def build_and_import_extension(
  13. modname, functions, *, prologue="", build_dir=None,
  14. include_dirs=None, more_init=""):
  15. """
  16. Build and imports a c-extension module `modname` from a list of function
  17. fragments `functions`.
  18. Parameters
  19. ----------
  20. functions : list of fragments
  21. Each fragment is a sequence of func_name, calling convention, snippet.
  22. prologue : string
  23. Code to precede the rest, usually extra ``#include`` or ``#define``
  24. macros.
  25. build_dir : pathlib.Path
  26. Where to build the module, usually a temporary directory
  27. include_dirs : list
  28. Extra directories to find include files when compiling
  29. more_init : string
  30. Code to appear in the module PyMODINIT_FUNC
  31. Returns
  32. -------
  33. out: module
  34. The module will have been loaded and is ready for use
  35. Examples
  36. --------
  37. >>> functions = [("test_bytes", "METH_O", \"\"\"
  38. if ( !PyBytesCheck(args)) {
  39. Py_RETURN_FALSE;
  40. }
  41. Py_RETURN_TRUE;
  42. \"\"\")]
  43. >>> mod = build_and_import_extension("testme", functions)
  44. >>> assert not mod.test_bytes('abc')
  45. >>> assert mod.test_bytes(b'abc')
  46. """
  47. if include_dirs is None:
  48. include_dirs = []
  49. body = prologue + _make_methods(functions, modname)
  50. init = """
  51. PyObject *mod = PyModule_Create(&moduledef);
  52. #ifdef Py_GIL_DISABLED
  53. PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED);
  54. #endif
  55. """
  56. if not build_dir:
  57. build_dir = pathlib.Path('.')
  58. if more_init:
  59. init += """#define INITERROR return NULL
  60. """
  61. init += more_init
  62. init += "\nreturn mod;"
  63. source_string = _make_source(modname, init, body)
  64. mod_so = compile_extension_module(
  65. modname, build_dir, include_dirs, source_string)
  66. import importlib.util
  67. spec = importlib.util.spec_from_file_location(modname, mod_so)
  68. foo = importlib.util.module_from_spec(spec)
  69. spec.loader.exec_module(foo)
  70. return foo
  71. def compile_extension_module(
  72. name, builddir, include_dirs,
  73. source_string, libraries=None, library_dirs=None):
  74. """
  75. Build an extension module and return the filename of the resulting
  76. native code file.
  77. Parameters
  78. ----------
  79. name : string
  80. name of the module, possibly including dots if it is a module inside a
  81. package.
  82. builddir : pathlib.Path
  83. Where to build the module, usually a temporary directory
  84. include_dirs : list
  85. Extra directories to find include files when compiling
  86. libraries : list
  87. Libraries to link into the extension module
  88. library_dirs: list
  89. Where to find the libraries, ``-L`` passed to the linker
  90. """
  91. modname = name.split('.')[-1]
  92. dirname = builddir / name
  93. dirname.mkdir(exist_ok=True)
  94. cfile = _convert_str_to_file(source_string, dirname)
  95. include_dirs = include_dirs or []
  96. libraries = libraries or []
  97. library_dirs = library_dirs or []
  98. return _c_compile(
  99. cfile, outputfilename=dirname / modname,
  100. include_dirs=include_dirs, libraries=libraries,
  101. library_dirs=library_dirs,
  102. )
  103. def _convert_str_to_file(source, dirname):
  104. """Helper function to create a file ``source.c`` in `dirname` that contains
  105. the string in `source`. Returns the file name
  106. """
  107. filename = dirname / 'source.c'
  108. with filename.open('w') as f:
  109. f.write(str(source))
  110. return filename
  111. def _make_methods(functions, modname):
  112. """ Turns the name, signature, code in functions into complete functions
  113. and lists them in a methods_table. Then turns the methods_table into a
  114. ``PyMethodDef`` structure and returns the resulting code fragment ready
  115. for compilation
  116. """
  117. methods_table = []
  118. codes = []
  119. for funcname, flags, code in functions:
  120. cfuncname = f"{modname}_{funcname}"
  121. if 'METH_KEYWORDS' in flags:
  122. signature = '(PyObject *self, PyObject *args, PyObject *kwargs)'
  123. else:
  124. signature = '(PyObject *self, PyObject *args)'
  125. methods_table.append(
  126. "{\"%s\", (PyCFunction)%s, %s}," % (funcname, cfuncname, flags))
  127. func_code = f"""
  128. static PyObject* {cfuncname}{signature}
  129. {{
  130. {code}
  131. }}
  132. """
  133. codes.append(func_code)
  134. body = "\n".join(codes) + """
  135. static PyMethodDef methods[] = {
  136. %(methods)s
  137. { NULL }
  138. };
  139. static struct PyModuleDef moduledef = {
  140. PyModuleDef_HEAD_INIT,
  141. "%(modname)s", /* m_name */
  142. NULL, /* m_doc */
  143. -1, /* m_size */
  144. methods, /* m_methods */
  145. };
  146. """ % {'methods': '\n'.join(methods_table), 'modname': modname}
  147. return body
  148. def _make_source(name, init, body):
  149. """ Combines the code fragments into source code ready to be compiled
  150. """
  151. code = """
  152. #include <Python.h>
  153. %(body)s
  154. PyMODINIT_FUNC
  155. PyInit_%(name)s(void) {
  156. %(init)s
  157. }
  158. """ % {
  159. 'name': name, 'init': init, 'body': body,
  160. }
  161. return code
  162. def _c_compile(cfile, outputfilename, include_dirs, libraries,
  163. library_dirs):
  164. link_extra = []
  165. if sys.platform == 'win32':
  166. compile_extra = ["/we4013"]
  167. link_extra.append('/DEBUG') # generate .pdb file
  168. elif sys.platform.startswith('linux'):
  169. compile_extra = [
  170. "-O0", "-g", "-Werror=implicit-function-declaration", "-fPIC"]
  171. else:
  172. compile_extra = []
  173. return build(
  174. cfile, outputfilename,
  175. compile_extra, link_extra,
  176. include_dirs, libraries, library_dirs)
  177. def build(cfile, outputfilename, compile_extra, link_extra,
  178. include_dirs, libraries, library_dirs):
  179. "use meson to build"
  180. build_dir = cfile.parent / "build"
  181. os.makedirs(build_dir, exist_ok=True)
  182. with open(cfile.parent / "meson.build", "wt") as fid:
  183. link_dirs = ['-L' + d for d in library_dirs]
  184. fid.write(textwrap.dedent(f"""\
  185. project('foo', 'c')
  186. py = import('python').find_installation(pure: false)
  187. py.extension_module(
  188. '{outputfilename.parts[-1]}',
  189. '{cfile.parts[-1]}',
  190. c_args: {compile_extra},
  191. link_args: {link_dirs},
  192. include_directories: {include_dirs},
  193. )
  194. """))
  195. native_file_name = cfile.parent / ".mesonpy-native-file.ini"
  196. with open(native_file_name, "wt") as fid:
  197. fid.write(textwrap.dedent(f"""\
  198. [binaries]
  199. python = '{sys.executable}'
  200. """))
  201. if sys.platform == "win32":
  202. subprocess.check_call(["meson", "setup",
  203. "--buildtype=release",
  204. "--vsenv", ".."],
  205. cwd=build_dir,
  206. )
  207. else:
  208. subprocess.check_call(["meson", "setup", "--vsenv",
  209. "..", f'--native-file={os.fspath(native_file_name)}'],
  210. cwd=build_dir
  211. )
  212. so_name = outputfilename.parts[-1] + get_so_suffix()
  213. subprocess.check_call(["meson", "compile"], cwd=build_dir)
  214. os.rename(str(build_dir / so_name), cfile.parent / so_name)
  215. return cfile.parent / so_name
  216. def get_so_suffix():
  217. ret = sysconfig.get_config_var('EXT_SUFFIX')
  218. assert ret
  219. return ret