Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dll in C++ for using in C#

I've a little question to ask you.

I have one C++ source and one header files. The C++ file uses windows.h library, makes operations using serial port(basic operations: read(), write() etc.).

What I want to do is, creating a library using these files, and use that library in my C#.Net solution.

What type of library I need to create? How can I do it? After creating library, How can I import it to C# solution?

My best regards.

Code Parts I'm using:

// 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 <stdexcept>

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;
    }
}

C# import part:

[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));
}
like image 237
unnamed Avatar asked Dec 03 '11 08:12

unnamed


People also ask

What is DLL in C programming?

In Windows, a dynamic-link library (DLL) is a kind of executable file that acts as a shared library of functions and resources. Dynamic linking is an operating system capability. It enables an executable to call functions or use resources stored in a separate file.

How compile DLL from source code?

Start by downloading the project from GitHub. Then open the solution file in Visual Studio and make the necessary changes to the source code. Then compile. Finally reference the compiled assembly into your application (don't use the official NuGet).


4 Answers

After several comments, here a try:

C++ Code (DLL), eg. math.cpp, compiled to HighSpeedMath.dll:

extern "C"
{
    __declspec(dllexport) int __stdcall math_add(int a, int b)
    {
        return a + b;
    }
}

C# Code, eg. Program.cs:

namespace HighSpeedMathTest
{
    using System.Runtime.InteropServices;

    class Program
    {
        [DllImport("HighSpeedMath.dll", EntryPoint="math_add", CallingConvention=CallingConvention.StdCall)]
        static extern int Add(int a, int b);

        static void Main(string[] args)
        {
            int result = Add(27, 28);
        }
    }
}

Of course, if the entry point matches already you don't have to specify it. The same with the calling convention.

As mentioned in the comments, the DLL has to provide a C-interface. That means, extern "C", no exceptions, no references etc.

Edit:

If you have a header and a source file for your DLL, it could look like this:

math.hpp

#ifndef MATH_HPP
#define MATH_HPP

extern "C"
{
    __declspec(dllexport) int __stdcall math_add(int a, int b);
}

#endif

math.cpp

#include "math.hpp"

int __stdcall math_add(int a, int b)
{
    return a + b;
}
like image 122
Simon Avatar answered Oct 06 '22 06:10

Simon


You need to compile your C++ code into a dynamic link library and do the following in C#:

  class MyClass
  {
  [DllImport("MyDLL.dll")]
  public static extern void MyFunctionFromDll();

        static void Main()
        {
              MyFunctionFromDll();
        }
  }
like image 45
Luchian Grigore Avatar answered Oct 06 '22 06:10

Luchian Grigore


You may use C# DllImport and Dllexport for DLL Interop walkthrough as a starting point. And here is the Platform Invoke Tutorial

Hope this helps.

like image 27
Eugene Cheverda Avatar answered Oct 06 '22 05:10

Eugene Cheverda


In addition to Lichian's offer to compile to a regular DLL and use p/invoke which is probably the simplest way You can also create your C++ as a COM component (probably something you don't want to do) and the 3rd option you have is to add a thin layer of C++/CLI e.g.

using namespace System;

namespace youcomany{ namespace CPPWrapper
{
    Wrapper::Function(String^ parameter)
    {
        //call the rest of you C++ from here
        }
}}
like image 27
Arnon Rotem-Gal-Oz Avatar answered Oct 06 '22 06:10

Arnon Rotem-Gal-Oz