下面演示如何从 c++ 注册 ac 回调函数,它一般有用,不是特定于 glut。
这是您的客户端 C++ 程序
int main(int argc, char *argv[]) {
std::cout << "launching Camera ..." << std::endl;
Camera * camera = new Camera();
// ------ glut new window boilerplate ------- //
int WindowHandle = 0;
glutInit(&argc, argv);
WindowHandle = glutCreateWindow("hello there");
if(WindowHandle < 1) {
std::cerr << "ERROR: Could not create a new rendering window" << std::endl;
exit(EXIT_FAILURE);
}
// ------------------------------------------ //
camera->setup_callback();
glutMainLoop();
return 0;
}
这是Camera.cpp
Camera * ptr_global_instance = NULL;
extern "C" void ReshapeCamera_callback(int width, int height) {
// c function call which calls your c++ class method
ptr_global_instance->ReshapeCamera_cb(width, height);
}
void Camera::ReshapeCamera_cb(int width, int height) {
std::cout << "width " << width << " height " << height << std::endl;
}
void Camera::setup_callback() {
// c++ method which registers c function callback
::ptr_global_instance = this;
::glutReshapeFunc(::ReshapeCamera_callback);
}
及其头文件 Camera.h
class Camera {
public:
void ReshapeCamera_cb(int width, int height);
void setup_callback();
};
注意 c++ 全局类指针 ptr_global_instance 的使用