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

前端 未结 4 1205
失恋的感觉
失恋的感觉 2020-12-28 09:27

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 operati

4条回答
  •  醉话见心
    2020-12-28 09:48

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

提交回复
热议问题