Question

I am using kernel32.dll to import a 3rd party DLL's functions via the method below.

private delegate bool MyDelegate(float[] floatArray, UInt16[] intArray);

private static MyDelegate MyDelegateCaller = null;

public static bool MyMethod(ref float[] floatArray, out UInt16[] intArray)
{
    if(MyDelegateCaller == null)
    {
        IntPtr address = GetProcAddress(_dllHandle, "ExternalMethod");

        MyDelegateCaller = 
            (MyDelegate)Marshal.GetDelegateForFunctionPointer(
                address, 
                typeof(MyDelegate)
            );
    }

    return MyDelegateCaller(floatArray, intArray); //*
}

If I debug and step over MyDelegateCaller (at //*) then the arrays get populated as expected. However, if I just run the code, the arrays do not get populated.

Any ideas as to what is going on?

Some more info: I am using this method rather than PInvoke for calling the DLL as I need to be able to unload and reload DLLs at run-time. I have tried adding delays, running in different threads as test to try to simulate the effect of stepping over. There isn't any cross thread calling of these methods, unless the DLL is creating its own thread(s), however, I do not have access to the DLL's code to verify.


Update

So I've tried the following (inspired from here)

            ...
            );
    }

    IAsyncResult result = MyDelegateCaller.BeginInvoke(floatArray, intArray, null, null);

    while (!result.IsCompleted)
        result.AsyncWaitHandle.WaitOne(1000, false); //**

    result.AsyncWaitHandle.Close();

    return MyDelegateCaller.EndInvoke(result);    
}

However, when I get to //** the program throws a System.ExecutionEngineException.


Hack

Got my code working.

I removed the working from the previous update and put MyMethod in a BackgroundWorker's DoWork event. Looped over BackgroundWorker.IsBusy.

Not elegant, but will do for the moment.

Any better solutions are more than welcome!

Was it helpful?

Solution

I have tried adding delays, running in different threads.

Adding arbitrary delays is not the right way to synchronize between threads. You need to wait for the other task to complete.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top