bounding brokenness


Over the weekend, I decided to learn js-ctypes. The best way to learn an API is by using it for something non-trivial, so I wrote a patch to move a bit of code calling Win32 functions I had written a few months ago from C to JavaScript. Overall, I was pleasantly surprised at how simple it is to use.

  • The documentation sucks a bit at the moment – I found that the best way to experiment was to use the xpcshell REPL. I’m sure this will be fixed in time for Firefox 4.0.
  • The js-ctypes type hierarchy makes complete sense. I haven’t used any other equivalents (python ctypes, .NET P/Invoke), but I hope they’re similar.
  • There is a good deal of type checking built into the API – more than I’m used to from a dynamic language, at any rate. If only JavaScript were statically typed…
  • Declaring Win32 types and functions is simple enough – just look them up on MSDN. Declaring constants can be harder, since not all constant values are provided on MSDN. To get some of them, I had to resort to grepping the Microsoft SDK include directory, and in a couple of cases writing and compiling small C programs to print the value.
  • Comparing pointers is annoying. That was probably what I spent the most time figuring out. I ultimately cast my voidptr_t into an intptr_t and worked with its value, which is a ctypes.Int64.
  • I hit one major gotcha – in JavaScript, the operands of bitwise operators are signed 32-bit integers. In particular, 0x80000000 | 0x40000000 = –0x40000000 and not 0xC0000000. This impacts how bit flags work. Ways to avoid this include adding up the flags instead (as long as you know all the flags you’re adding are mutually exclusive) or simply using the composite flag.

Other than these two things, if you already have the C code in front of you, translating it to JavaScript line by line is quite straightforward. I didn’t deal with callbacks, so I’m sure there will be some added complexity there.