开发者

Accessing protected memory in C# via COM interop

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 thi开发者_如何学Gos 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜