Reputation: 63
How can I set a type's Guid dynamically?
Silly question, but I have an interface that is the exact same across several third-party COM Objects, but has a different GUID in each.
I have a C# interface that looks like so.
[Guid("1F13D3D8-3071-4125-8011-900D2EAC9A7F")]
[InterfaceType(2)]
[TypeLibType(4240)]
public interface UICtrl
{
//stuff
}
I want to be able to change the GUID dynamically at run time depending on which COM object the user chooses to load. I can't change the meta data, and Type.Guid has no set property. Any ideas?
I can't use Remit.Emit because the calling assembly doesn't use it. I'm really stuck!
Upvotes: 1
Views: 464
Reputation: 63
So I ended up fixing this by using a part of @SLaks's answer and my own. Basically I took my parent interface and generated a child interface from it which had the GUID I wanted.
AssemblyName aName = new AssemblyName("MulticasterAssembly");
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run);
ModuleBuilder mb = ab.DefineDynamicModule("MulticasterModule");
TypeBuilder tb = mb.DefineType("MainOCXMultiCaster", TypeAttributes.Public);
tb.SetParent(typeof(AxUICtrlEventMulticaster));
ConstructorInfo cInfo = typeof(GuidAttribute).GetConstructor(new Type[] {typeof(string)});
CustomAttributeBuilder cab = new CustomAttributeBuilder(cInfo, new object[] { mOCXType.GUID.ToString() });
tb.SetCustomAttribute(cab);
ConstructorBuilder cb = tb.DefineDefaultConstructor(MethodAttributes.Public);
Type childEventMulticaster = tb.CreateType();
object o = Activator.CreateInstance(childEventMulticaster);
childEventMulticaster.InvokeMember("host", BindingFlags.SetProperty, null, o, new object[] { this });
Upvotes: 1
Reputation: 888067
Try making three empty [Guid]
'd interfaces which inherit a base interface with all of the members.
Upvotes: 0