gpt4 book ai didi

d - 如何轻松地初始化函数指针?

转载 作者:行者123 更新时间:2023-12-03 03:40:21 26 4
gpt4 key购买 nike

我想使用 Runtime.loadLibraryGetProcAddress(...) 加载 Win32 API 函数。使用mixin:

template GetProcA(alias func, alias name_in_DLL)
{
const char[] GetProcA = func ~ ` = cast(typeof(`~func~`)) GetProcAddress(hModule,"`~name_in_DLL~`");`;
}
...
static extern (Windows) Object function (HWND hWnd, int nIndex) GetWindowLong;
static extern (Windows) Object function (HWND hWnd, int nIndex, Object dwNewLong) SetWindowLong;

我可以这样实例化它(在类构造函数中):

mixin GetProcA!("SetWindowLong", "SetWindowLongA");

但是如果再次将其用于另一个功能:

mixin GetProcA!("GetWindowLong", "GetWindowLongA");

编译器提示:

mixin GetProcA!("GetWindowLong","GetWindowLongA") GetProcA isn't a template...

我不明白这一点:如果第一个实例化创建了 GetProcA 并且我无法再次使用它,那么它对我有什么帮助?

最佳答案

从你的代码来看,你想要一个 mixin expression ,不是template mixin :

string GetProcA(string func, string name_in_dll)
{
return func ~ ` = cast(typeof(` ~ func ~ `)) ` ~
`GetProcAddress(hModule,"` ~ name_in_dll ~ `");`;
}

mixin(GetProcA("SetWindowLong", "SetWindowLongA"));
mixin(GetProcA("GetWindowLong", "GetWindowLongA"));

实际上,你甚至不需要 mixin。一个内部模板函数就足够了:

hModule = ...;

void GetProcA(T)(ref T func, string name_in_all)
{
func = cast(typeof(func)) GetProcAddress(hModule, toStringz(name_in_all));
}

GetProcA(SetWindowLong, "SetWindowLongA");
GetProcA(GetWindowLong, "GetWindowLongA");

关于d - 如何轻松地初始化函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8805687/

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