How do I mix C# and C++ code in a single assembly?


This is an FAQ posted internally. Share it with everyone.


It applies to .Net framework 2.0 beta2+.


How do I mix C# and C++ code in a single assembly?


 


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.

Comments (5)

  1. Mike says:

    How about the opposite — is there an "easy" (relatively) way to take a mixed mode assembly and decompile it to the il + native code chunk?

  2. junfeng says:

    I have no idea.

  3. Scott Hanselman says:

    Does this not work in .NET 1.1?

  4. junfeng says:

    No it does not work in .Net 1.1

  5. Marius says:

    Do you have a simple sample showing the cs and cpp code?