dlopen(None) fails on Windows

Issue #325 on hold
created an issue

I am interested in getting started with CFFI, so I was looking at the tutorial. This part ran fine:

>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi.cdef("""
...     int printf(const char *format, ...);   // copy-pasted from the man page
... """)

However, as soon as I ran C = ffi.dlopen(None), I got

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python36\lib\site-packages\cffi\api.py", line 140, in dlopen
    lib, function_cache = _make_ffi_library(self, name, flags)
  File "C:\Python36\lib\site-packages\cffi\api.py", line 786, in _make_ffi_library
    backendlib = _load_backend_lib(backend, libname, flags)
  File "C:\Python36\lib\site-packages\cffi\api.py", line 781, in _load_backend_lib
    raise OSError(msg)
OSError: ctypes.util.find_library() did not manage to locate a library called 'c'

The correct thing to do on Windows is to ffi.dlopen('msvcrt.dll'), which is the c runtime on Windows. (though I believe cffi should probably handle this itself)

Comments (5)

  1. Armin Rigo

    What occurs with ffi.dlopen(None) depends on the version of Python and the version of Windows. Can you confirm the following points:

    • are you running Python 3.x?

    • does ffi.dlopen('msvcrt.dll') work as expected on your version of Windows?

    • can you check if ffi.dlopen(None) works as expected running on the same version of Windows but on Python 2.7?

    If the answers are positive, I could try msvcrt after trying c.

  2. ethanhs reporter

    Hello Armin, as you can tell from the stack trace, I am running Python 3.6. ffi.dlopen(None) does work as expected on Python 2.7.13 and 3.4.4. It fails on 3.5.4 and 3.6.2 due to the newer Microsoft compilers. Technically, you want to load the library pointed to by ctypes.util.find_msvcrt, however on Python 3.5+ this just returns None, which is due to the bug as you posted. Perhaps a note in the docs for now would be sufficient, but a fix to the Python bug is of course the best solution 😄

  3. Armin Rigo

    The whole situation sounds like a mess. I'm very very unsure that ffi.dlopen('msvcrt') will do what people expect: although it will certainly do something that seems right at a first glance, it will load a different C standard library and endless confusion will follow.

    I think I'll not add any more hacks inside CFFI and stay with the documentation already written, unless someone comes along with more precise knowledge (answering all of my questions above would be a start, but is not sufficient).

  4. Log in to comment