Search code examples
javascriptcfirefoxfirefox-addonfgets

FF addon: How to declare C function fgets in javascript


I'm developing firefox plugin and I want to read file using WinApi. I manage to connect with WinApi and it works fine.

var lib = ctypes.open("user32.dll");
var msgBox = lib.declare("MessageBoxW",
                       ctypes.winapi_abi,
                       ctypes.int32_t,
                       ctypes.int32_t,
                       ctypes.jschar.ptr,
                       ctypes.jschar.ptr,
                       ctypes.int32_t);
var MB_OK = 0;
var ret = msgBox(0, "Hello world", "title", MB_OK);

Now I declare fopen:

const FILE = new ctypes.StructType("FILE").ptr;   
var fopen = libc.declare("fopen",                     // symbol name
                        ctypes.default_abi,           // cdecl calling convention
                        FILE,                         // return type (FILE*)
                        ctypes.char.ptr,              // first arg (const char*)
                        ctypes.char.ptr);             // second arg (const char*)

but I fail to declare fgets. I still can't figure it out. I try to do:

var libc = ctypes.open("msvcrt.dll");
var fgets = libc.declare("fgets",                    
                        ctypes.default_abi,           
                        ctypes.char.ptr,              
                        ctypes.char.ptr,              
                        ctypes.int32_t,               
                        FILE);                        
// Call the function, and get a FILE* pointer object back.
console.log(LOG_FILTER, "Try to open file.");
var file1 = fopen("1.in", "r");

  var SIZE = 100;
  var line = ctypes.char(SIZE).ptr;
  line = fgets(line, SIZE, file1);` 

I think I don't use wrong library because then I would get error "Error: couldn't find function symbol in library" but I still get "TypeError: expected type pointer, got (void 0)"


Solution

  • So here is my solution. I decided to use getc function instead of fgets and I manage to read file.

    Components.utils.import("resource://gre/modules/ctypes.jsm");
    var libc = ctypes.open("msvcrt.dll");
    
    // int getc(FILE *stream);
    var getc = libc.declare("getc",
                            ctypes.default_abi,
                            ctypes.int32_t,
                            FILE);
    var file = fopen("newfile.in", "w");
    var readFile = readFileToString(file)
    
    function readFileToString(file) {
      var result = '';
      var c = 0;
      while((c = getc(file)) != -1) {
        result += String.fromCharCode(c); 
      }
      console.log("result = " + result);
      return result;
    }