If you are running 32-bit 3.6 on Windows, please test this

eryk sun eryksun at gmail.com
Fri Sep 1 18:06:14 EDT 2017


On Fri, Sep 1, 2017 at 3:23 AM, Peter Otten <__peter__ at web.de> wrote:
>
> I think you have to specify the types yourself:
>
>>>> import ctypes
>>>> libm = ctypes.cdll.LoadLibrary("libm.so")
>>>> libm.sqrt(42)
> 0
>>>> libm.sqrt.argtypes = [ctypes.c_double]
>>>> libm.sqrt.restype = ctypes.c_double
>>>> libm.sqrt(42)
> 6.48074069840786

On POSIX systems, use ctypes.util.find_library('m'), which, for
example, resolves to "libm.so.6" in Ubuntu Linux 16.04. On the same
system, "libm.so" is an ld script that's used by the compile-time
linker.

    $ cat /usr/lib/x86_64-linux-gnu/libm.so
    /* GNU ld script
    */
    OUTPUT_FORMAT(elf64-x86-64)
    GROUP ( /lib/x86_64-linux-gnu/libm.so.6
        AS_NEEDED (
            /usr/lib/x86_64-linux-gnu/libmvec_nonshared.a
            /lib/x86_64-linux-gnu/libmvec.so.1 ) )

The runtime linker doesn't know how to handle this script.

    >>> ctypes.CDLL('libm.so')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python3.5/ctypes/__init__.py",
        line 347, in __init__
        self._handle = _dlopen(self._name, mode)
    OSError: /usr/lib/x86_64-linux-gnu/libm.so: invalid ELF header

On Windows, Python 3.5+ uses the Universal C Runtime. You can
reference it directly as follows:

    ucrt = ctypes.CDLL('ucrtbase', use_errno=True)

But in practice you should use the math API set [1]. For example:

    >>> crt_math = ctypes.CDLL('api-ms-win-crt-math-l1-1-0',
    ...     use_errno=True)
    >>> crt_math.sqrt.restype = ctypes.c_double
    >>> crt_math.sqrt.argtypes = [ctypes.c_double]
    >>> crt_math.sqrt(1.3)
    1.140175425099138
    >>> ctypes.get_errno()
    0

Note that find_library('c') and find_library('m') both return None
under Windows in Python 3.5+.

    >>> ctypes.util.find_library('c') is None
    True
    >>> ctypes.util.find_library('m') is None
    True

[1]: https://msdn.microsoft.com/en-us/library/mt656782#_api-ms-win-crt-math-l1-1-0



More information about the Python-list mailing list