2013-05-05 10 views

risposta

7

Se si ottiene un puntatore a funzione da una funzione C, è necessario verificare che sia interpretato correttamente come puntatore a FunctionType. Quindi puoi semplicemente chiamarlo come se fosse una funzione JavaScript. Ad esempio, GetProcAddress() restituisce un puntatore a funzione - nel seguente codice Dichiaro GetProcAddress() con un puntatore nullo come tipo di ritorno, poi ho gettato che puntatore a un tipo di funzione corrispondente alla firma della funzione MessageBox():

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); 
Problemi correlati