do function casts ever disappear?

  • From: William Adams <william_a_adams@xxxxxxx>
  • To: <luajit@xxxxxxxxxxxxx>
  • Date: Fri, 20 Jul 2012 17:48:11 +0000

With the recent discussions on callabacks, I begain to doubt my OpenGL 
extension implementation.

What am I trying to achieve:  OpenGL has a number of extension functions.  The 
only way to get at those functions is to get a pointer to the function by way 
of a library call, then cast that to a function prototype, and make the call.

Doubt:  Does the function pointer cast ever become invalid/garbage collected, 
unintentionally?

Code:

ffi.cdef[[

 typedef int (__attribute__((__stdcall__)) *PROC)();
 PROC wglGetProcAddress(LPCSTR lpszProc);

typedef void (* PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, GLchar* 
*string, const GLint *length);
]]

function GetFunctionProtoName(fname)
 local upname = fname:upper();
 local protoname = string.format("PFN%sPROC", upname);
 return protoname;
end

function CastFunctionPointer(fname, funcptr)
 local protoname = GetFunctionProtoName(fname);
 local castfunc = ffi.cast(protoname, funcptr);
 return castfunc;
end

function GetWglFunction(fname)
 local funcptr = gl.wglGetProcAddress(fname);
 if funcptr == nil then
  return nil
 end
 local castfunc = CastFunctionPointer(fname, funcptr);
 return castfunc;
end

OglMan={}
OglMan_mt = {
 __index = function(tbl, key)
  local funcptr = GetWglFunction(key)
  -- Set the function into the table of
  -- known functions, so next time around,
  -- it this code will not need to execute
  rawset(tbl, key, funcptr)
  return funcptr;
 end,
}

Which allows for this:

OglMan.glShaderSource(self.ID, 1, src_array, nil);

Questions:
In GetWglFunction(), I get the pointer to the function using wglGetProcAddress. 
 Looking at it now, I think the return value of PROC should be intptr_t, but 
the real question is:  Will the cast being one in CastFunctionPointer() stick 
around forever, or is there any magic that will make it disappear when I least 
expect it?  This isn't a callback, so I don't think the callback slots are any 
influence, but still, I have a doubt as to how many function pointers can live.

I'm holding onto the cast within the table, along with the key, which is the 
function name.  Is that sufficient to keep the cast around?

-- William

===============================
- Shaping clay is easier than digging it out of the ground.
http://williamaadams.wordpress.com
https://github.com/Wiladams                                       

Other related posts: