如何在C++中创建dll以便在C#中使用

bak*_*kar 10 c# c++ dll serial-port

我有一个问题要问你.

我有一个C++源代码和一个头文件.C++文件使用windows.h库,使用串口进行操作(基本操作:read(),write()等).

我想要做的是,使用这些文件创建一个库,并在我的C#.Net解决方案中使用该库.

我需要创建什么类型的库?我该怎么做?创建库后,如何将其导入C#解决方案?

我最诚挚的问候.

我正在使用的代码部件:

// 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

C#import部分:

[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));
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*mon 9

经过多次评论,请试试:

C++代码(DLL),例如.math.cpp,编译为HighSpeedMath.dll:

extern "C"
{
    __declspec(dllexport) int __stdcall math_add(int a, int b)
    {
        return a + b;
    }
}
Run Code Online (Sandbox Code Playgroud)

C#代码,例如.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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,如果入口点已经匹配,则不必指定它.与调用约定相同.

如评论中所述,DLL必须提供C接口.这意味着,extern"C",没有例外,没有引用等.

编辑:

如果您有DLL的标头和源文件,它可能如下所示:

math.hpp

#ifndef MATH_HPP
#define MATH_HPP

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

#endif
Run Code Online (Sandbox Code Playgroud)

math.cpp

#include "math.hpp"

int __stdcall math_add(int a, int b)
{
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*ore 5

您需要将C++代码编译为动态链接库,并在C#中执行以下操作:

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

        static void Main()
        {
              MyFunctionFromDll();
        }
  }
Run Code Online (Sandbox Code Playgroud)