我正在开发一个用 c++ 编码并用 ctypes 包装的简单引擎。我正在研究窗口类,我想让引擎用户能够设置绘制和更新功能。我有以下代码:
窗口.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*);
};
窗口.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使用单独的类/接口(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 .它将应用程序的窗口方面与绘图功能清晰地分开。
关于c++ - 将成员函数指针设置为空闲函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63268941/