ravi.joshi53's picture

AccessViolationException while migrating from TAO to OpenTK

My windows application which was using TAO earlier is now in process of shifting to OpenTK. In TAO, I noticed that there were no load and paint event. However as suggested here , I am using load event in OpenTK, the way it is described in the post.

The application is having a dock panel attached to main form. The OpenTK initialization (i.e. load event) is placed in main form and from dock panel there is some rendering being done. Up to this it was working in TAO. But it is throwing below error with OpenTK-

System.AccessViolationException was unhandled
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=OpenTK
  StackTrace:
       at OpenTK.Graphics.OpenGL.GL.GenLists(Int32 range)

I realized that from doc panel calling GL.any_method is throwing the same error. It seems to me that OpenTK is not loaded yet~


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

Try adding a call to glControl1.CreateControl() before using any GL. functions in your Load event.

This error usually means that you are calling OpenGL functions before the OpenGL context has been created. You either need to wait until the GLControl has been constructed (GLControl.HandleCreated event) or force its construction through the CreateControl method.

Needless to say, this issue is independent of Tao / OpenTK (indeed, it was a very common bug back when taoframework.com still existed.) Due to the internal architecture, Tao and OpenTK 1.0 may not crash when calling OpenGL 1.1 functions without an OpenGL context (depending on the function / driver), but both will crash if you call any OpenGL 1.2 - 4.4 functions. OpenTK 1.1 uses a different (faster) p/invoke method that will always throw an exception if an OpenGL context does not exist.

ravi.joshi53's picture

Great Thanks Fiddler,

Still I am facing the same issue. I have observed that load event is being fired later and by that time the doc panel is calling GL.function. How to prevent this scenario? Should i put sleep before calling doc panel? sounds weird to me :(

the Fiddler's picture

Well, the easiest way to prevent this scenario is to only call GL functions from GLControl events. For example, instead of Form.Load, you could use GLControl.Load to setup your OpenGL resources.

If you need to add GL calls to a generic WinForms Control, then you need to make sure that a GraphicsContext is available. You can check if GraphicsContext is available using:

if (GraphicsContext.CurrentContext != null)
{
    // Safe to use GL calls
}

A GraphicsContext is created as part of GLControl, so in general all you need to do is call GLControl.CreateControl() or GLControl.MakeCurrent() first.

ravi.joshi53's picture

Thanks a ton fiddler... it works....