gpt4 book ai didi

firefox-addon - 如何在js-ctypes中使用指针调用函数

转载 作者:行者123 更新时间:2023-12-04 06:11:52 24 4
gpt4 key购买 nike

我只有一个指向函数的指针,如何在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);

关于firefox-addon - 如何在js-ctypes中使用指针调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16381893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com