Skip to content

Instantly share code, notes, and snippets.

@xHeaven
Forked from Paskowsky/COMObject.cs
Created July 30, 2020 10:36
Show Gist options
  • Save xHeaven/5e14c43a0d99f79ecc145777f553d65a to your computer and use it in GitHub Desktop.
Save xHeaven/5e14c43a0d99f79ecc145777f553d65a to your computer and use it in GitHub Desktop.
public class COMObject
{
private object self;
private Type COMType;
public static COMObject Create(string name)
{
return new COMObject(Activator.CreateInstance(Type.GetTypeFromProgID(name)));
}
public COMObject(object obj)
{
self = obj;
COMType = COMHelpers.GetManagedComType(self);
#if DEBUG
DumpMethods(COMType);
#endif
}
public object Value
{
get
{
return self;
}
}
public object InvokeMember(string name, BindingFlags invokeAttrs, params object[] args)
{
return COMType.InvokeMember(name, invokeAttrs, null, self, args);
}
#if DEBUG
private static void DumpMethods(Type t)
{
StringBuilder sb = new StringBuilder();
Console.WriteLine(new string('-', 20));
Console.WriteLine(t.ToString());
Console.WriteLine();
foreach (MethodInfo m in t.GetMethods())
{
Console.WriteLine(m);
sb.AppendLine(m.ToString());
}
File.WriteAllText(t.Name + ".txt", sb.ToString());
}
#endif
static class COMHelpers
{
[ComImport, Guid("00020400-0000-0000-C000-000000000046"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IDispatch
{
void Reserved();
int GetTypeInfo(uint nInfo, int lcid, out IntPtr typeInfoPtr);
}
internal static Type GetManagedComType(object instance)
{
IDispatch id = (IDispatch)instance;
IntPtr tPtr;
id.GetTypeInfo(0, Thread.CurrentThread.CurrentCulture.LCID, out tPtr);
return Marshal.GetTypeForITypeInfo(tPtr);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment