Skip to content

Using X11 through ffi on windows does not work

When using the X11 Xlib through the ffi instead of using the existing binding on linux it works fine. On windows it does not. I have written similar programs, with the same result. I have had no problems like this before.

I link with the "libX11-6" library, which comes with X11 for cygwin. the "libX11-6" is the only choise. Can not find anything else to use. This particular lib works fine if writing an equivalent program in C and explicitly linking with it using GCC.

Strangely, if the argument to XOpenDisplay is wrong, the function actually returns, and with a 0, which makes sense since it failed. Same result on linux, but this is the only case where it actually works on windows. If the argument is 0, then the function seems to correctly read the DISPLAY environment variable, and then if that is invalid the function returns 0, otherwise the program crashes/hangs.


A program that uses ffi to access the X11 Xlib. Works fine on linux, but on win2k + cygwin:

  • using:

    > ghc --make no_c_test.hs -ffi -L"Y:\cygwin\usr\X11R6\lib" -llibX11-6 -fglasgow-exts

    when run, it crashes with: "The instruction at "0x00000000" referenced memory

    at "0x00000000". The memory could not be "read".

  • using:

    > (same as above, but adding any of: -fvia-C -O -O2 )

    when run, it seems to go into an infinite loop after printing "before".

import Foreign.C.String (withCString, CString)
import Foreign.Ptr (Ptr)
import Foreign.C.Types (CInt)

foreign import ccall safe "XOpenDisplay"
  openDisplay :: CString -> IO (Ptr DisplayStruct)

foreign import ccall safe "XCloseDisplay"
  closeDisplay :: Ptr DisplayStruct -> IO CInt

data DisplayStruct

main :: IO ()
main = do
  withCString "localhost:0.0" $ \cstr -> do
  print "before"
  p <- openDisplay cstr
  print "after"
  closeDisplay p
  print "done"

Another example, but instead partially using C code. Works fine on linux, but not on windows.

If writing the program entirely in C, it works. But if replacing main in the C program with a call from haskell code through ffi, then it does not work anymore.

c-file:

#include <X11/Xlib.h>
#include <stdio.h>

void ProgFunc(){
      printf("ProgFunc starting\n");
      Display *dpy = XOpenDisplay(":0.0");
      printf("dpy: 0x%x\n", (unsigned int)dpy);
}

/*  it works if using this main. (thus only C code compiled with GCC)
main()
{
        ProgFunc();
        return 0;
}
*/

haskell-file:

import System.IO
foreign import ccall unsafe "ProgFunc" progFunc :: IO ()
main :: IO ()
main = do
  print "before c"
  progFunc
  print "after c"
Trac metadata
Trac field Value
Version 6.6
Type Bug
TypeOfFailure OtherFailure
Priority high
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture Unknown
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information