Search code examples
visual-studiovisual-studio-2019c++-cliclr

Embed Interop Types property is missing in CLR Project


I have a CLR Empty Project (.NET Framework 4.6.2) I've noticed that the Embed Interop Types is not present in the References Properties, I couldn't find a workaround, is there a way to turn it on? It looks like it's only available on C#.


Solution

  • I come up with the following workaround:

    Add the particular assembly you want to embed into your project, right click on it, select Properties then set Item Type to Compiled Managed Resource and put the following snippet at the first lines inside the main:

    [System::STAThread]
    int main()
    {
        System::AppDomain::CurrentDomain->AssemblyResolve += gcnew System::ResolveEventHandler(&loadEmbeddedAssembly);
    }
    

    And at somewhere there:

    System::Reflection::Assembly^ loadEmbeddedAssembly(System::Object^ sender, System::ResolveEventArgs^ args) {
    
        System::Reflection::AssemblyName^ assemblyName = gcnew System::Reflection::AssemblyName(args->Name);
    
        System::String^ resourceName = assemblyName->Name + ".dll";
    
        System::IO::Stream^ stream = System::Reflection::Assembly::GetExecutingAssembly()->GetManifestResourceStream(resourceName);
    
        array<System::Byte>^ assemblyData = gcnew array<System::Byte>((unsigned long)stream->Length);
        try {
            stream->Read(assemblyData, 0, assemblyData->Length);
        }
        finally {
            if (stream != nullptr) delete stream;
        }
    
        return System::Reflection::Assembly::Load(assemblyData);
    }