How call virtual function in COM in C#

182 Views Asked by At

I am new to COM and C#. What I am trying to do is rewriting the following source in C#:

explife.c

explife.h

typedef interface IARPUninstallStringLauncher IARPUninstallStringLauncher;

typedef struct IARPUninstallStringLauncherVtbl {

BEGIN_INTERFACE

    HRESULT(STDMETHODCALLTYPE *QueryInterface)(
        __RPC__in IARPUninstallStringLauncher * This,
        __RPC__in REFIID riid,
        _COM_Outptr_  void **ppvObject);

    ULONG(STDMETHODCALLTYPE *AddRef)(
        __RPC__in IARPUninstallStringLauncher * This);

    ULONG(STDMETHODCALLTYPE *Release)(
        __RPC__in IARPUninstallStringLauncher * This);

    HRESULT(STDMETHODCALLTYPE *LaunchUninstallStringAndWait)(
        __RPC__in IARPUninstallStringLauncher * This,
        _In_ HKEY hKey,
        _In_ LPCOLESTR Item,
        _In_ BOOL bModify,
        _In_ HWND hWnd);

    HRESULT(STDMETHODCALLTYPE *RemoveBrokenItemFromInstalledProgramsList)(
        __RPC__in IARPUninstallStringLauncher * This,
        _In_ HKEY hKey,
        _In_ LPCOLESTR Item);

END_INTERFACE

} *PIARPUninstallStringLauncherVtbl;

interface IARPUninstallStringLauncher
{
  CONST_VTBL struct IARPUninstallStringLauncherVtbl *lpVtbl;
};

From what I understood he reversed functions in this interface and created a structure so that he can reach to address of this virtual function.

Functions in this COM is not viewable in OLEVIEW and also I can't import it in VisualStudio.

My question is that it is possible to write it in C#?

1

There are 1 best solutions below

1
On BEST ANSWER

This would be a C# equivalent (you don't need to define IUnknown methods, and this is implicit):

[Guid("F885120E-3789-4FD9-865E-DC9B4A6412D2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IARPUninstallStringLauncher
{
    [PreserveSig]
    int LaunchUninstallStringAndWait(
            IntPtr hKey,
            [MarshalAs(UnmanagedType.LPWStr)] string Item,
            bool bModify,
            IntPtr hWnd);

    [PreserveSig]
    int RemoveBrokenItemFromInstalledProgramsList(
        IntPtr hKey,
        [MarshalAs(UnmanagedType.LPWStr)] string Item);
}

You can declare the coclass like this (yes, with an empty body)

[Guid("FCC74B77-EC3E-4DD8-A80B-008A702075A9"), ComImport]
public class UninstallStringLauncher
{
}

And to create and use the object, you can try a code like this

var launcher = (IARPUninstallStringLauncher)new UninstallStringLauncher();

And make sure the bitness (x86/x64) of your COM object matches the bitness of your C# app.