从 D-to-C 回调访问 D 对象时出现访问冲突错误

Access Violation Error when accessing D object from D-to-C callback

我最近开始涉足 DerelictGLFW。我有两个 classes,其中一个是 Window class,另一个是 InputHandler class(window 事件的事件管理器) .在我的光标位置回调中,我使用 window 用户指针并尝试设置位置,但在尝试设置回调和 GLFW 之外的任何值时,我立即收到访问冲突错误。 GLFW 被初始化,并且不报告任何错误。谢谢你的时间。

Class Window
{
    private:
        double cursorX;

    ...other stuffs...

    @property
    void cursorX(double x) nothrow
    {
        cursorX = x;
    }
}

extern(C) void mousePosCallback(GLFWwindow* window, double x, double y)
{
    Window* _window = window.userPointer 
    //userPointer is a static function that gets the window user pointer
    //and casts it to a Window*

    _window.cursorX = x;
}

static Window* userPointer(GLFWwindow* window)
{
    return cast(Window*) glfwGetWindowUserPointer(window);
}

编辑:

已将 extern(C) 添加到回调,错误仍然存​​在。

已将 "immediately upon entering the callback" 更正为 "immediately upon attempting to set any value outside of the callback and GLFW"。

向问题

添加了userPointer函数

mousePosCallback 必须在 extern(C) 块中声明。这是为了使调用约定匹配。

extern (C) void mousePosCallback(GLFWwindow* window, double x, double y)
{
    Window* _window = window.userPointer 
    //userPointer is a static function that gets the window user pointer
    //and casts it to a Window*

    _window.cursorX = x;
}

看来我找到错误的根源了。在 window 初始化期间,我尝试使用 this 设置用户指针。我不确定为什么,但是将它移到另一个未从构造函数调用的函数中似乎可以解决问题。问题解决了,但是谁能帮我理解为什么?这对我来说似乎很奇怪。