Windows Store App中的ComImport

时间:2012-04-10 20:04:26

标签: c# .net windows-runtime windows-store-apps

现在看来这个属性现在映射到CoCreateInstanceFromApp,它过滤掉你可以创建的COM(基本没用 - 没有第三方等)。

所以我想问你是否知道一些简单的方法来实例化已经存在并使用GUID在系统上注册的COM?

我设法只做这样的黑客攻击(但这非常麻烦,只是为了防止微软阻止我做我一直做的事情而且没有问题):

[ComVisible(true), ComImport,
 Guid("00000001-0000-0000-C000-000000000046"),
 InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IClassFactory
{
    [PreserveSig]
    int CreateInstance([In, MarshalAs(UnmanagedType.Interface)] object pUnkOuter,
                       ref Guid riid,
                       [Out, MarshalAs(UnmanagedType.Interface)] out object obj);

    [PreserveSig]
    int LockServer([In] bool fLock);
}

[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String procname);

internal delegate int DllGetClassObjectDelegate([MarshalAs(UnmanagedType.LPStruct)] Guid clsid,[MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

void LoadItDamnit() {
    IntPtr dll = LoadLibrary(path);
    IntPtr proc = GetProcAddress(dll, "DllGetClassObject");

    var getClassObject = (DllGetClassObjectDelegate)Marshal.GetDelegateForFunctionPointer(proc, typeof(DllGetClassObjectDelegate));

    int hr = getClassObject(IMYLIB_GUID, IUNKNOWN_GUID, out oFactory);

    IClassFactory factory = oFactory as IClassFactory;

    if (factory == null)
    {
           if (oFactory != null) Marshal.ReleaseComObject(oFactory);
           throw new Exception("Could not QueryInterface for the IClassFactory interface");
    }

    Guid myGUID = typeof(IMyInterface).GetGUID();
    hr = factory.CreateInstance(null, ref myGUID, out oMyObj);

    _obj = oMyObj as IMyInterface;
 }

如您所见,这需要在路径中使用dll(或使用其他API来更改当前路径)以及加载库,并且实现本来应该可用的内容有点过于篡改... < / p>

如果有人知道更好的方法来实例化任何COM对象并且更容易克服Metro的限制,我会买啤酒!

0 个答案:

没有答案