Search code examples
c++.netcommand-lineunmanageddllexport

Include managed C# DLL into unmanaged C++ DLL - all in one single file


Intro : How do I combine an unmanaged dll and a managed assembly into one file?

In comparison to the question above i need to combine DLLs so that final mixed DLL could export their functions to other unmanaged applications.

For this i would like to compile them both as .netmodule and then combine them into one file with a linker so i have :

1) Libs - project with some library in C# - it does not have any dependencies and and i can easily compile it like a .netmodule

2) Links - C++ unmanaged project that has reference to C# library and unfortunately i am not able to build it with cl.exe compiler because it always gives an error saying that namespace from C# library cannot be found even though i tried to point compiler to all folders where it can find reference to my C# assembly, this C++ project is used like a simple C++ wrapper over CLR methods from C#

Here is my batch script and second line throws an error :

"c:/Windows/Microsoft.NET/Framework/v4.0.30319/csc.exe" /target:module /out:./Build/libs.netmodule Libs\Properties\*.cs Libs\*.cs
"c:/Program Files/Microsoft Visual Studio 12.0/VC/bin/cl.exe" /clr /AI"D:\T\CPlus\Library\Release" /AI"D:\T\CPlus\Library\Libs" /AI"D:\T\CPlus\Library\Libs\Properties" /LN Links\*.cpp

Question : does anybody now how to let C++ know where it can find C# assembly to resolve the reference or maybe i need to somehow explicitly mention my header files in batch commands?

Source code : C# is just empty class with method Foo and C++ looks like this one.

// Links.h

#pragma once

#define DllExport extern "C" __declspec(dllexport)

using namespace System;
using namespace Libs; // cl.exe cannot resolve this reference

// Links.cpp

#include "Links.h"

DllExport int __stdcall Execute()
{
    Libs::CLibrary::Foo();
}

Solution

  • Here is the final working version.

    "c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /target:module /out:Libs.netmodule /recurse:..\Libs\*.cs
    "c:\Program Files\Microsoft Visual Studio 12.0\VC\bin\cl.exe" /clr /LN /Fo /Y- /Z7 /FU Libs.netmodule ..\Links\Links.cpp /link /LIBPATH:"c:\Program Files\Microsoft Visual Studio 12.0\VC\lib" /LIBPATH:"c:\Program Files\Microsoft SDKs\Windows\v7.1A\Lib"
    "c:\Program Files\Microsoft Visual Studio 12.0\VC\bin\link.exe" /DLL /LTCG /CLRIMAGETYPE:IJW /OUT:Library.dll Libs.netmodule Links.obj /LIBPATH:"c:\Program Files\Microsoft Visual Studio 12.0\VC\lib" /LIBPATH:"c:\Program Files\Microsoft SDKs\Windows\v7.1A\Lib"
    

    Useful links :

    Now i am able to use exported functions from .NET in unmanaged applications. Moreover, all information from both projects - Links (C++) and Libs (C#) - was grouped in one file - Library.dll. This way i can merge into one DLL as many projects as i want and it does not matter whether they are managed or native.