views:

208

answers:

1

I am making a DLL "Plugin" for a EXE. The EXE calls a function in the DLL with an Object as a parameter, and goes from there.

It all works fine and dandy until I split it to a new thread. This error happens

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

when executing this code on the object in the new thread:

    protected object GetPropertyValue(object obj, string PropertyName)
    {
        return obj.GetType().InvokeMember(PropertyName, BindingFlags.GetProperty, null, obj, new object[] { });
    }

The above is trying to access a property on a COM object. Changing the function to 'public' doesn't affect it. The code works just fine however if I'm using just one thread.

What's happening is clear: The new thread does not have access to the variable in the EXE. How can I fix this? Not using a thread is not a viable option.

Appreciate any help

+1  A: 

Your COM object probably exists in the STA. That means you need to dispatch back to the thread that owns the object, and make the call from there.

If the COM object supports free threading, then it might be running in the STA because your main method is marked with the STA thread attribute.

Alternatively, if you control the COM object you could trying making it an MTA object.

In that case, try removing that attribute. However, if you are using Windows forms, then your forms have to be created from an STA thread.

Scott Wisniewski
I have no control over the COM object
Lynxy
But you do have control over the thread that invokes it. If it's an STA com object, you have to access it from the thread that owns it (the thread where it was created).
Scott Wisniewski
Alternatively, try adding setting the BG thread to use the STA when you create it. If you do that I beleive the CLR will handle the thread dispatch for you (using the message loop).To that just call thread.SetAppartmemtState
Scott Wisniewski
Thanks, that has done the trick! I made the original thread proxy it over
Lynxy