Skip to content

Instantly share code, notes, and snippets.

@yajd
Last active August 29, 2015 13:56
Show Gist options
  • Save yajd/9241275 to your computer and use it in GitHub Desktop.
Save yajd/9241275 to your computer and use it in GitHub Desktop.
fgets noit version - ctypes works but its weird. copy paste this to scratchpad with environment set to browser
Cu.import("resource://gre/modules/ctypes.jsm");
var libc = ctypes.open("msvcrt.dll");
var struct_FILE = new ctypes.StructType("FILE"); //set to var only so can run multiple times in scratchpad, can change back to const
var fopen = libc.declare("fopen", // symbol name
ctypes.default_abi, // cdecl calling convention
struct_FILE.ptr, // return type (FILE*)
ctypes.char.ptr, // first arg (const char*)
ctypes.char.ptr); // second arg (const char*)
var fgetc = libc.declare("fgetc", // symbol name
ctypes.default_abi, // cdecl calling convention
ctypes.int.ptr, // return type (FILE*)
struct_FILE.ptr); // second arg (const char*)
var fgets = libc.declare("fgets", // symbol name
ctypes.default_abi, // cdecl calling convention
ctypes.jschar.ptr, // return char pointer
ctypes.jschar.ptr, // first arg char pointer
ctypes.int, //second arg int
struct_FILE.ptr); // third arg FILE pointer
var myfile = fopen("C:\\Users\\3K2KYC1\\Desktop\\FirefoxPortable\\newfile.in", "r");
//Services.wm.getMostRecentWindow(null).alert(myfile);
var line = new ctypes.jschar;
var ret = fgets(line.address(), 2, myfile);
Services.wm.getMostRecentWindow(null).alert(line);
Services.wm.getMostRecentWindow(null).alert(ret);
//newfile.in already exists and its contents is "ABC" no quotes
//using size 2 as 2nd arg on line 30
//line - is set to "ctypes.jschar("A")" no quotes, which is the first char in the file, but i said get 2 char why didnt it give first 2 chars if try 3 it gives something weird
//ret - is set to "ctypes.jschar.ptr(ctypes.UInt64("0xfba2b32"))"
//if use size of 3:
//line - "ctypes.jschar("\u4241")"
//ret - "ctypes.jschar.ptr(ctypes.UInt64("0x8fefce8"))"
@yajd
Copy link
Author

yajd commented Feb 27, 2014

Rev2

I learned on MSDN if it has * next to name it means it's a pointer so fixed the code above. Also changed FILE to struct_FILE, as good practice you dont set itself to .ptr I'm thinking, it just makes sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment