How to use C++ code in C#

Why cannot use C++ code in C# directly?

The most remarkable difference between C++ and C# ,i think ,is C++ is unmanaged language rather C# is managed ,which determined you can not write C++ code into the C# code directly,otherwise ,unmanaged code will seems like a runaway train in the managed code

How many ways to use C++ code in C#?

in my opinion ,the ways to use C++ code in C# depends on what you want to call.i just briefly list two type that you want call:

  • C++ function
  • C++ Class
Call C++ function by using Platform Invocation(PInvoke)

PInvoke allows for managed code to call native unmanaged functions implemented as DLLs.this method is ideal for when we have API-like function written in C or C++ that need to be accessed from within a C# program.

NOTE:PInvoke only can be used to Marshall function not to CLass.

The diagram below summarise the PInvake mechanism.

A PInvoke example

Step1 : create Dll project

there is a link aboutcreate DLL project in VS2017

Continue reading “How to use C++ code in C#”