我只有一个指向函数的指针,如何在js-ctypes中调用它?
谢谢。
如果您从 C 函数中获得函数指针,那么您需要确保它被正确解释为指向FunctionType的指针。然后,您可以像调用 JavaScript 函数一样简单地调用它。例如,GetProcAddress()
返回一个函数指针——在下面的代码中,我声明GetProcAddress()
一个 void 指针作为返回类型,然后我将该指针转换为与函数签名匹配的函数类型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);