将成员函数指针设置为自由函数指针



我正在开发一个用c++编码并用ctypes封装的简单引擎。我正在处理窗口类,我想让引擎用户能够设置绘制和更新功能。我有以下代码:

window.h

#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
class window
{
public:
GLFWwindow* wnd;
window(int width, int height, const char* title);
void close();
void update();
void (window::*draw)();
void setDrawFunction(void (window::*)());
void setUpdateFunction(int*);
};

window.cpp

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "window.h"
void default_draw() {
glClear(GL_COLOR_BUFFER_BIT);
}
void default_update() {

}
window::window(int width, int height, const char* title)
{
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_COMPAT_PROFILE, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
wnd = glfwCreateWindow(width, height, title, NULL, NULL);
if (wnd == NULL) { glfwTerminate(); return; }
glfwMakeContextCurrent(wnd);
if (glewInit() != GLEW_OK) {
glfwTerminate();
return;
}
setDrawFunction((void)(window::*)()default_draw);
}
void window::close() {
glfwDestroyWindow(this->wnd);
}
void window::update() {
default_update();
}
void window::setDrawFunction(void (window::*fnptr)()) {
draw = fnptr;
}

这行不通。我是错过了一些显而易见的东西,还是不可能以这种方式完成。如果是的话,我有什么办法可以做到这一点吗?我所需要的只是能够过驱动函数,所以我可以在python中使用ctypes来实现这一点。

我收到的错误:调用前的109表达式必须具有函数(指针(类型应为29表达式预期18"(">

window的成员函数指针用作成员变量是不合适的。

我可以想出以下办法来解决这个问题。

选项1

draw设为非成员函数指针。

void (*draw)();
void setDrawFunction(void (*func)());

选项2

使draw成为std::function

std::function<void()> draw;
void setDrawFunction(std::function<void()> func);

选项3

使用分离器类/接口进行绘图。

std::unique_ptr<DrawingAgent> draw;
void setDrawingAgent(std::unique_ptr<DrawingAgent> agent);

其中

class DrawingAgent
{
public:
virtual void draw(window*); // Draw in given window.
};

在上述选项中,我建议使用选项3。它将应用程序的窗口方面与绘图功能完全分离。

最新更新