Techno Barje

JS Ctypes

Bug 518721 - Implement jsctypes with raw JSAPI
Status: SOLVED FIXED!!!

That’s an awesome news for mozilla’s developpers!
JS Ctypes aims to provide the same library than Python Ctypes :

You can load any dynamic library (dll, so, dylib) and call C-functions directly from your Javascript. In the current implementation only simple types are supported : numbers, string, boolean. For now, we can’t play with pointers, nor structures, but these features are planned.


simpler code -> less work -> simpler review

This new feature is going to greatly ease platform specific developpement like windows management, system calls, … For example we’re able to call Windows API directly from Javascript, without having to create, compile and maintain any C++ XPCOM!
One side effect is that it will ease code review for https://addons.mozilla.org/ too! Instead of shipping an obscure dynamic library with our extension, we may build only a JS-Ctypes wrapper and call directly OS libraries or call a common library that can be validated by reviewers with some MD5 checks.


simpler code -> less knownledge -> better learning curve

This is going to simplify the use of native code too! You can now build native code without having to learn any mozilla "things" (XPCOM, specific build layout/system, …) You will just have to expose your library with a C api and write a simple JS-CTypes wrapper.


Hello World!

  • First retrieve Firefox 3.6b1pre nightly or Firefox 3.7a1pre nightly
  • On windows, copy and paste this code in your JS console.
    This will display an OS native dialog.
    (Change the dll path if your main windows directory is not on C:\WINDOWS!)
    /* Load JS Ctypes Javascript module */
    Components.utils.import("resource://gre/modules/ctypes.jsm");
    var Types = ctypes.types;
    
    /* Load windows api dll */
    var lib = ctypes.open("C:\\WINDOWS\\system32\\user32.dll");
    
    /* Declare the signature of the function we are going to call */
    var msgBox = lib.declare("MessageBoxW",
                             ctypes.stdcall_abi,
                             ctypes.int32_t,
                             ctypes.int32_t,
                             ctypes.ustring,
                             ctypes.ustring,
                             ctypes.int32_t);
    var MB_OK = 3;
    
    /* Do it! */
    var ret = msgBox(0, "Hello world", "title", MB_OK);
    
    /* Display the returned value */
    alert("MessageBox result : "+ret);
    
    lib.close();