Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function using pointer in js-ctypes

I only have a pointer to a function, how to call it in js-ctypes?

Thanks.

like image 481
yume_chan Avatar asked May 05 '13 06:05

yume_chan


1 Answers

If you got a function pointer from a C function then you need to make sure it's correctly interpreted as a pointer to FunctionType. Then you can simply call it as you would a JavaScript function. For example, GetProcAddress() returns a function pointer - in the following code I declare GetProcAddress() with a void pointer as return type, then I cast that pointer to a function type matching the signature of the MessageBox() function:

Components.utils.import("resource://gre/modules/ctypes.jsm");

var BOOL = ctypes.int32_t;
var HANDLE = ctypes.voidptr_t;
var HMODULE = HANDLE;
var HWND = HANDLE;
var FARPROC = ctypes.voidptr_t;
var LPCTSTR = ctypes.jschar.ptr;
var LPCSTR = ctypes.char.ptr;

var kernel = ctypes.open("kernel32.dll");
var LoadLibrary = kernel.declare(
    "LoadLibraryW",
    ctypes.winapi_abi,
    HMODULE, // return type
    LPCTSTR // parameters
);
var FreeLibrary = kernel.declare(
    "FreeLibrary",
    ctypes.winapi_abi,
    BOOL, // return type
    HMODULE // parameters
);
var GetProcAddress = kernel.declare(
    "GetProcAddress",
    ctypes.winapi_abi,
    FARPROC, // return type
    HMODULE, LPCSTR // parameters
);

// Load the library we're interested in.
var hUser = LoadLibrary("user32");

// Get the pointer to the function.
var MessageBox = GetProcAddress(hUser, "MessageBoxW");

// Now we have a pointer to a function, let's cast it to the right type.
var MessageBoxType = ctypes.FunctionType(
    ctypes.winapi_abi,
    ctypes.int32_t, // return type
    [HWND, LPCTSTR, LPCTSTR, ctypes.uint32_t] // parameters
);
MessageBox = ctypes.cast(MessageBox, MessageBoxType.ptr);

// Actually call the function.
MessageBox(null, "Test1", "Test2", 0);

// Free the library again if no longer needed. Any imported function
// pointers should be considered invalid at this point.
FreeLibrary(hUser);
like image 141
Wladimir Palant Avatar answered Nov 15 '22 13:11

Wladimir Palant