title: How to create dll in C++ for using in C#
body: <p>I've a little question to ask you.</p>
  
  <p>I have one C++ source and one header files. The C++ file uses windows.h library, makes operations using serial port(basic operations: <strong>read(), write()</strong> etc.).</p>
  
  <p>What I want to do is, creating a library using these files, and use that library in my <strong>C#.Net solution</strong>.</p>
  
  <p>What type of library I need to create?
  How can I do it?
  After creating library, How can I import it to C# solution?</p>
  
  <p>My best regards.</p>
  
  <p><strong>Code Parts I'm using:</strong></p>
  
  <pre><code>// MathFuncsDll.h
  
  namespace MathFuncs
  {
      class MyMathFuncs
      {
      public:
          // Returns a + b
          static __declspec(dllexport) double Add(double a, double b);
  
          // Returns a - b
          static __declspec(dllexport) double Subtract(double a, double b);
  
          // Returns a * b
          static __declspec(dllexport) double Multiply(double a, double b);
  
          // Returns a / b
          // Throws DivideByZeroException if b is 0
          static __declspec(dllexport) double Divide(double a, double b);
      };
  }
  
  // MathFuncsDll.cpp
  // compile with: /EHsc /LD
  
  #include "MathFuncsDll.h"
  
  #include &lt;stdexcept&gt;
  
  using namespace std;
  
  namespace MathFuncs
  {
      double MyMathFuncs::Add(double a, double b)
      {
          return a + b;
      }
  
      double MyMathFuncs::Subtract(double a, double b)
      {
          return a - b;
      }
  
      double MyMathFuncs::Multiply(double a, double b)
      {
          return a * b;
      }
  
      double MyMathFuncs::Divide(double a, double b)
      {
          if (b == 0)
          {
              throw new invalid_argument("b cannot be zero!");
          }
  
          return a / b;
      }
  }
  </code></pre>
  
  <p><strong>C# import part:</strong></p>
  
  <pre><code>[DllImport("SimpleDll.dll", CallingConvention=CallingConvention.Cdecl)]
  public static extern double Add(double a, double b);
  
  static void Main(string[] args)
  {
      string a = Add(1.0, 3.0));
  }
  </code></pre>