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

前端 未结 4 1200
失恋的感觉
失恋的感觉 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;
    }
    
    0 讨论(0)
  • 2020-12-28 09:52

    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
            }
    }}
    
    0 讨论(0)
  • 2020-12-28 09:59

    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.

    0 讨论(0)
  • 2020-12-28 10:00

    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();
            }
      }
    
    0 讨论(0)
提交回复
热议问题