我正在研究一个用c++编码并用ctypes包装的简单引擎。我正在研究窗口类,我想让引擎用户能够设置绘制和更新功能。我有以下代码:
窗口
#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;
}
这行不通。我是否遗漏了一些明显的东西,或者根本无法通过这种方式完成。如果是这样,我有什么办法可以实现?我所需要的只是能够超载功能,因此我可以使用ctypes在python中做到这一点。我得到的错误:
调用前的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使用单独的类/接口(interface)进行绘图。
std::unique_ptr<DrawingAgent> draw;
void setDrawingAgent(std::unique_ptr<DrawingAgent> agent);
哪里class DrawingAgent
{
public:
virtual void draw(window*); // Draw in given window.
};
在上述选项中,我建议使用选项3 。它将应用程序的窗口外观与绘图功能完全分开。