user3636973
user3636973

Reputation: 11

Combining C# and C++ Code in a single Executable

How can I C# and C++ Code in a single Executable and will the Final Exe need Net Framework. I am using Visual Studio 2013.

Upvotes: 0

Views: 1403

Answers (2)

Shlomi Borovitz
Shlomi Borovitz

Reputation: 1700

Another way, which would work with any managed assembly (written in C++/CLI, or any .Net language) is to add that assembly as a resource to your executable project. So if that assembly does not appear in the directory with your exe, it would be loaded from resources with the following code.

In your exe, you should register to the assembly resolve event:

AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
    {
        Assembly asm = null;

        if (e.Name == "otherAssembly.dll")
        {
            byte[] assemblyBytes = // code to retrieve assembly from resources.
            asm = Assembly.Load(assemblyBytes);
        }

        return asm;
    };

Upvotes: 0

Rakib
Rakib

Reputation: 7615

From here

If your C++ code is not compiled with /clr:safe (i.e. it is compiled with /clr or /clr:pure), do the following:

  1. compile your C++ code into .obj files
  2. compile your C# code into a .netmodule, using /AddModule to reference the C++ .obj files
  3. link the C# .netmodule directly with the C++ object files using the C++ linker to create a mixed language assembly

If your C++ code is compiled with /clr:safe, build your C++ code as a .netmodule. You can use it just like you would use a .netmodule from any other language.

Here is a sample.

Here in great detail

Upvotes: 1

Related Questions