我目前正在将代码重构为一个类(
VkAPP
),并偶然发现了这个错误:
“void (VkAPP::)(GLFWwindow window, int width, int height)”类型的参数与“GLFWwindowsizefun”类型的参数不兼容
这是有问题的函数:
void onWindowResized(GLFWwindow* window, int width, int height) {
VkSurfaceCapabilitiesKHR surfaceCapabilities;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevices[0], surface, &surfaceCapabilities);
if (width > surfaceCapabilities.maxImageExtent.width) width = surfaceCapabilities.maxImageExtent.width;
if (height > surfaceCapabilities.maxImageExtent.height) height = surfaceCapabilities.maxImageExtent.height;
if (width == 0 || height == 0) return;
WIDTH = width;
HEIGHT = height;
recreateSwapchain();
}
电话如下:
glfwSetWindowSizeCallback(window, onWindowResized);
函数和调用在同一个类中。
如果我把它变成:
static void onWindowResized
我得到:
非静态成员引用必须相对于特定对象
对于
physicalDevices[0]
、surface
、WIDTH
、HEIGHT
和 recreateSwapchain()
成员函数原型
void onWindowResized(GLFWwindow* window, int width, int height);
实际上看起来像这样
void onWindowResized(
ClassType *this, //the famously infamous 'this' pointer
GLFWwindow* window,
int width,
int height
);
要将函数用作回调,该函数必须是全局函数或在类中声明为静态。
但是您需要一种解决方法来访问类的成员。
GLFW 提供了一种通过
存储用户指针的机制void glfwSetWindowUserPointer(GLFWwindow *window, void *pointer);
并通过
检索它void* glfwGetWindowUserPointer(GLFWwindow *window);
要完成所有工作,您必须进行一些修改
//either global or inside class
static void onWindowResized(GLFWwindow* window, int width, int height)
{
//get your class instance
MyClass *obj = reinterpret_cast<MyClass*>(glfwGetWindowUserPointer(window);
//use the memebers as usual
//obj->physicalDevices[0];
//obj->surface;
//obj->WIDTH;
//obj->HEIGHT;
//obj->recreateSwapchain();
}
不要忘记将您的类实例与窗口相关联
//somewhere in your code (but before the callback gets invoked)
glfwSetWindowUserPointer(window, /* MyClass* */ obj);
注意:密切关注类实例的生命周期
obj
。