Skip to content

LoadLibrary¤

Load a library.

LoadLibrary ¤

LoadLibrary(path, libtype=None, **kwargs)

Load a library.

For example, a C/C++, FORTRAN, .NET, Java, Delphi, LabVIEW, ActiveX, ... library.

Parameters:

Name Type Description Default
path PathLike

The path to the library. The search order to find the library is:

  1. assume that a full or a relative (to the current working directory) path is specified
  2. use ctypes.util.find_library
  3. search sys.path
  4. search os.environ["PATH"].

If loading a COM library, path may either be the

  • ProgID (e.g, "InternetExplorer.Application"), or the
  • CLSID (e.g., "{2F7860A2-1473-4D75-827D-6C4E27600CAC}").
required
libtype LibType | None

The library type. The following values are supported:

  • cdll: a library that uses the __cdecl calling convention (default value if not specified and not a Java library)
  • windll or oledll: a library that uses the __stdcall calling convention
  • net or clr: a .NET library (Common Language Runtime)
  • java: a Java archive (.jar or .class files)
  • com: a COM library
  • activex: an ActiveX library

Tip

Since the .jar or .class extension uniquely defines a Java library, libtype will automatically be set to java if path ends with .jar or .class.

Support for library types were added in the following msl-loadlib versions

  • 0.1: __cdecl, __stdcall, .NET
  • 0.4: Java
  • 0.5: COM
  • 0.9: ActiveX
None
kwargs Any

All additional keyword arguments are passed to the object that loads the library. If libtype is

{}

Raises:

Type Description
OSError

If the library cannot be loaded.

ValueError

If the value of libtype is not supported.

Source code in src/msl/loadlib/load_library.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def __init__(self, path: PathLike, libtype: LibType | None = None, **kwargs: Any) -> None:  # noqa: C901, PLR0912, PLR0915
    """Load a library.

    For example, a C/C++, FORTRAN, .NET, Java, Delphi, LabVIEW, ActiveX, ... library.

    Args:
        path: The path to the library.
            The search order to find the library is:

            1. assume that a full or a relative (to the current working directory) path is specified
            2. use [ctypes.util.find_library][]{:target="_blank"}
            3. search [sys.path][]{:target="_blank"}
            4. search [os.environ["PATH"]][os.environ]{:target="_blank"}.

            If loading a [COM]{:target="_blank"} library, `path` may either be the

            * ProgID (e.g, `"InternetExplorer.Application"`), or the
            * CLSID (e.g., `"{2F7860A2-1473-4D75-827D-6C4E27600CAC}"`).

            [COM]: https://learn.microsoft.com/en-us/windows/win32/com/component-object-model--com--portal

        libtype: The library type.
            The following values are supported:

            * `cdll`: a library that uses the `__cdecl` calling convention
                (default value if not specified and not a Java library)
            * `windll` or `oledll`: a library that uses the `__stdcall` calling convention
            * `net` or `clr`: a .NET library (Common Language Runtime)
            * `java`: a Java archive (`.jar` or `.class` files)
            * `com`: a [COM]{:target="_blank"} library
            * `activex`: an [ActiveX]{:target="_blank"} library

            [COM]: https://learn.microsoft.com/en-us/windows/win32/com/component-object-model--com--portal
            [ActiveX]: https://learn.microsoft.com/en-us/windows/win32/com/activex-controls

            !!! tip
                Since the `.jar` or `.class` extension uniquely defines a Java library,
                `libtype` will automatically be set to `java` if `path` ends with
                `.jar` or `.class`.

            !!! note "Support for library types were added in the following `msl-loadlib` versions"
                * 0.1: __cdecl, __stdcall, .NET
                * 0.4: Java
                * 0.5: COM
                * 0.9: ActiveX

        kwargs: All additional keyword arguments are passed to the object that loads the library.
            If `libtype` is

            * `cdll` → [ctypes.CDLL][]{:target="_blank"}
            * `windll` → [ctypes.WinDLL][]{:target="_blank"}
            * `oledll` → [ctypes.OleDLL][]{:target="_blank"}
            * `net` or `clr` → all keyword arguments are ignored
            * `java` → [JavaGateway][py4j.java_gateway.JavaGateway]{:target="_blank"}
            * `com` → [comtypes.CreateObject][CreateObject]{:target="_blank"}
            * `activex` → [Application.load][msl.loadlib.activex.Application.load]

    Raises:
        OSError: If the library cannot be loaded.
        ValueError: If the value of `libtype` is not supported.
    """
    # a reference to the ActiveX application
    self._app: Application | None = None

    # a reference to the library
    self._lib: Any = None

    # a reference to the .NET Runtime Assembly
    self._assembly: Any = None

    # a reference to the Py4J JavaGateway
    self._gateway: Any = None

    if not path:
        msg = f"Must specify a non-empty path, got {path!r}"
        raise ValueError(msg)

    # fixes Issue #8, if `path` is a <class 'pathlib.Path'> object
    path = os.fsdecode(path)

    _libtype: str
    if libtype is None:  # noqa: SIM108
        _libtype = "java" if path.endswith((".jar", ".class")) else "cdll"
    else:
        _libtype = libtype.lower()

    if _libtype not in _LIBTYPES:
        msg = f"Invalid libtype {_libtype!r}\nMust be one of: {', '.join(_LIBTYPES)}"
        raise ValueError(msg)

    # create a new reference to `path` just in case the
    # default_extension is appended below so that the
    # ctypes.util.find_library function call will use the
    # unmodified value of `path`
    _path = path

    # assume a default extension if no extension was provided
    _, ext = os.path.splitext(path)
    if not ext and _libtype not in {"java", "com", "activex"}:
        _path += default_extension

    self._path: str
    if _libtype not in {"com", "activex"}:
        file = os.path.abspath(_path)
        if os.path.isfile(file):
            self._path = file
        else:
            # for find_library use the original 'path' value since it may be a library name
            # without any prefix like 'lib', suffix like '.so', '.dylib' or version number
            file2 = ctypes.util.find_library(path)
            if file2 is None:  # then search sys.path and os.environ['PATH']
                success = False
                search_dirs = sys.path + os.environ["PATH"].split(os.pathsep)
                for directory in search_dirs:
                    p = os.path.join(directory, _path)
                    if os.path.isfile(p):
                        self._path = p
                        success = True
                        break
                if not success:
                    msg = f"Cannot find {path!r} for libtype={_libtype!r}"
                    raise OSError(msg)
            else:
                self._path = file2
    else:
        self._path = _path

    if _libtype == "cdll":
        self._lib = ctypes.CDLL(self._path, **kwargs)
    elif _libtype == "windll":
        self._lib = ctypes.WinDLL(self._path, **kwargs)
    elif _libtype == "oledll":
        self._lib = ctypes.OleDLL(self._path, **kwargs)
    elif _libtype == "com":
        if not is_comtypes_installed():
            msg = "Cannot load a COM library because comtypes is not installed.\nRun: pip install comtypes"
            raise OSError(msg)

        from comtypes import (  # type: ignore[import-untyped] # pyright: ignore[reportMissingTypeStubs]
            GUID,  # pyright: ignore[reportUnknownVariableType]
        )
        from comtypes.client import (  # type: ignore[import-untyped] # pyright: ignore[reportMissingTypeStubs]
            CreateObject,  # pyright: ignore[reportUnknownVariableType]
        )

        try:
            clsid = GUID.from_progid(self._path)  # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
        except (TypeError, OSError):
            msg = f"Cannot find {path!r} for libtype='com'"
            raise OSError(msg) from None

        self._lib = CreateObject(clsid, **kwargs)

    elif _libtype == "activex":
        from .activex import Application

        self._app = Application()
        self._lib = self._app.load(self._path, **kwargs)

    elif _libtype == "java":
        if not is_py4j_installed():
            msg = "Cannot load a Java file because Py4J is not installed.\nRun: pip install py4j"
            raise OSError(msg)

        from py4j.java_gateway import (  # type: ignore[import-untyped] # pyright: ignore[reportMissingTypeStubs]
            GatewayParameters,  # pyright: ignore[reportUnknownVariableType]
            JavaGateway,  # pyright: ignore[reportUnknownVariableType]
        )
        from py4j.version import (  # type: ignore[import-untyped] # pyright: ignore[reportMissingTypeStubs]
            __version__,  # pyright: ignore[reportUnknownVariableType]
        )

        # find the py4j*.jar file (needed to import the py4j.GatewayServer on the Java side)
        filename = f"py4j{__version__}.jar"
        py4j_jar = os.environ.get("PY4J_JAR", "")
        if py4j_jar:
            if not os.path.isfile(py4j_jar) or os.path.basename(py4j_jar) != filename:
                msg = (
                    f"A PY4J_JAR environment variable exists, "
                    f"but the full path to {filename} is invalid\n"
                    f"PY4J_JAR={py4j_jar}"
                )
                raise OSError(msg)
        else:
            root = os.path.dirname(sys.executable)
            for item in [root, os.path.dirname(root), os.path.join(os.path.expanduser("~"), ".local")]:
                py4j_jar = os.path.join(item, "share", "py4j", filename)
                if os.path.isfile(py4j_jar):
                    break
            if not os.path.isfile(py4j_jar):
                msg = (
                    f"Cannot find {filename}\n"
                    f"Create a PY4J_JAR environment variable to be equal to the full path to {filename}"
                )
                raise OSError(msg)

        gp = kwargs.pop("gateway_parameters", GatewayParameters(address="127.0.0.1", port=get_available_port()))

        # build the java command
        wrapper = os.path.join(os.path.dirname(__file__), "py4j-wrapper.jar")
        cmd = ["java", "-cp", f"{py4j_jar}{os.pathsep}{wrapper}", "Py4JWrapper", str(gp.port)]

        # from the URLClassLoader documentation:
        #   Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL
        #   is assumed to refer to a JAR file which will be downloaded and opened as needed.
        if ext == ".jar":
            cmd.append(self._path)
        else:  # it is a .class file
            cmd.append(f"{os.path.dirname(self._path)}/")

        try:
            # start the py4j.GatewayServer
            flags = 0x08000000 if IS_WINDOWS else 0  # fixes issue 31, CREATE_NO_WINDOW = 0x08000000
            _ = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, creationflags=flags)  # noqa: S603
        except OSError as e:
            err = str(e).rstrip()
            err += "\nYou must have a Java Runtime Environment installed and available on PATH"
            raise OSError(err) from None

        try:
            wait_for_server(gp.address, gp.port, 10.0)
        except OSError as e:
            err = str(e).rstrip()
            err += "\nCould not start the Py4J GatewayServer"
            raise OSError(err) from None

        self._gateway = JavaGateway(gateway_parameters=gp, **kwargs)

        self._lib = self._gateway.jvm  # pyright: ignore[reportUnknownMemberType]

    elif _libtype in {"net", "clr"}:
        if not is_pythonnet_installed():
            msg = "Cannot load a .NET Assembly because pythonnet is not installed.\nRun: pip install pythonnet"
            raise OSError(msg)

        import clr  # type: ignore[import-untyped] # pyright: ignore[reportMissingTypeStubs]
        import System  # type: ignore[import-not-found] # pyright: ignore[reportMissingImports]

        dotnet = {"System": System}

        # the library must be available in sys.path
        head, tail = os.path.split(self._path)
        sys.path.insert(0, head)

        System: Any  # type: ignore[no-redef] # noqa: N806  # cSpell: ignore redef
        try:  # noqa: SIM105
            # don't include the library extension
            clr.AddReference(os.path.splitext(tail)[0])  # pyright: ignore[reportUnknownMemberType]
        except (System.IO.FileNotFoundException, System.IO.FileLoadException):
            # The file must exist since its existence is checked above.
            # There must be another reason why loading the DLL raises this
            # error. Calling LoadFile (below) provides more information
            # in the error message.
            pass

        try:
            # By default, pythonnet can only load libraries that are for .NET 4.0+
            #
            # In order to allow pythonnet to load a library from .NET <4.0 the
            # useLegacyV2RuntimeActivationPolicy property needs to be enabled
            # in a <python-executable>.config file. If the following statement
            # raises a FileLoadException then attempt to create the configuration
            # file that has the property enabled and then notify the user why
            # loading the library failed and ask them to re-run their Python
            # script to load the .NET library.
            self._assembly = System.Reflection.Assembly.LoadFile(self._path)

        except System.IO.FileLoadException as err:
            # Example error message that can occur if the library is for .NET <4.0,
            # and the useLegacyV2RuntimeActivationPolicy is not enabled:
            #
            # " Mixed mode assembly is built against version 'v2.0.50727' of the
            #  runtime and cannot be loaded in the 4.0 runtime without additional
            #  configuration information. "
            if str(err).startswith("Mixed mode assembly is built against version"):
                py_exe = sys.executable
                if sys.prefix != sys.base_prefix:
                    # Python is running in a venv/virtualenv
                    # When using conda environments, sys.prefix == sys.base_prefix
                    py_exe = os.path.join(sys.base_prefix, os.path.basename(py_exe))
                status, msg = check_dot_net_config(py_exe)
                if status == 0:
                    msg = f"Checking .NET config returned {msg!r} and still cannot load the library.\n{err}"
                raise OSError(msg) from err

            msg = "The above 'System.IO.FileLoadException' is not handled.\n"
            raise OSError(msg) from err

        try:
            types = self._assembly.GetTypes()
        except Exception as e:  # noqa: BLE001
            logger.error(e)
            logger.error("The LoaderExceptions are:")
            for item in e.LoaderExceptions:  # type: ignore[attr-defined] # pyright: ignore[reportUnknownMemberType,reportAttributeAccessIssue,reportUnknownVariableType]
                logger.error("  %s", item.Message)  # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
        else:
            for t in types:
                try:
                    obj = __import__(t.Namespace) if t.Namespace else getattr(__import__("clr"), t.FullName)
                except:  # noqa: E722
                    obj = t
                    obj.__name__ = t.FullName

                if obj.__name__ not in dotnet:
                    dotnet[obj.__name__] = obj

        self._lib = DotNet(self._path, dotnet)

    else:
        msg = "Should not get here -- contact developers"
        raise AssertionError(msg)

    logger.debug("Loaded %s", self._path)

application property ¤

application

Application | None — Reference to the ActiveX application window.

If the loaded library is not an ActiveX library, returns None.

When an ActiveX library is loaded, the window is not shown (to show it call Application.show) and the message loop is not running (to run it call Application.run).

Added in version 1.0

assembly property ¤

assembly

Returns a reference to the .NET Runtime Assembly object.

If the loaded library is not a .NET library, returns None.

Tip

The JetBrains dotPeek program can be used to decompile a .NET Assembly.

gateway property ¤

gateway

JavaGateway | None — Reference to the Java gateway.

If the loaded library is not a Java library, returns None.

lib property ¤

lib

Returns the reference to the library object.

For example, if libtype is

path property ¤

path

str — The path to the library file.

cleanup ¤

cleanup()

Clean up references to the library.

Added in version 0.10

Source code in src/msl/loadlib/load_library.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def cleanup(self) -> None:
    """Clean up references to the library.

    !!! note "Added in version 0.10"
    """
    self._assembly = None
    self._lib = None
    if self._gateway:
        self._gateway.shutdown()
        self._gateway = None
        logger.debug("shutdown Py4J.GatewayServer")
    if self._app:
        self._app.close()
        self._app = None
        logger.debug("close ActiveX application")