Question

Here is a piece of code:

private static bool CreateDelegates ()
{
     IntPtr ptr;

     //--- SoundTouch: createInstance

     ptr = Kernel32Methods.GetProcAddress (libHandle, "_soundtouch_createInstance@0");

     if (ptr != IntPtr.Zero)
     {
         createInstance = (st_createInstance) Marshal.GetDelegateForFunctionPointer
                          (ptr, typeof (st_createInstance));
     }

     //--- SoundTouch: destroyInstance

     ptr = Kernel32Methods.GetProcAddress (libHandle, "_soundtouch_destroyInstance@4");

     if (ptr != IntPtr.Zero)
     {
         destroyInstance = (st_destroyInstance) Marshal.GetDelegateForFunctionPointer
                           (ptr, typeof (st_destroyInstance));
     }
}

And there is many more assigments like above in this method. I want to create method like AssignProc (...) to reduce amount of code.

void AssignProc (string procName, Delegate d, Type??? )
{
    IntPtr ptr;

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName);

    if (ptr != IntPtr.Zero)
    {
        d = (Type???) Marshal.GetDelegateForFunctionPointer
                          (ptr, typeof (???));
    }
}

Where:

 private static st_createInstance        createInstance;

 [UnmanagedFunctionPointer (CallingConvention.StdCall)]
 private delegate IntPtr st_createInstance ();

Help?:)

Was it helpful?

Solution

I guess you want a generic method:

T CreateDelegate<T>(string procName) where T : class
{
    IntPtr ptr;

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName);

    if (ptr != IntPtr.Zero)
    {
        return (T)(object)Marshal.GetDelegateForFunctionPointer(ptr, typeof (T));
    }

    return null;
}

Unfortunately, you can't constrain T to a delegate, so you first have to cast the result of GetDelegateForFunctionPointer to object before casting it to T.

Usage:

createInstance = CreateDelegate<st_createInstance>("_soundtouch_createInstance@0");
destroyInstance = CreateDelegate<st_destroyInstance>("_soundtouch_destroyInstance@4");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top