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

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

C#导入部分:

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

最佳答案

经过多次评论,这里试一试:

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

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

C# 代码,例如。程序.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);
        }
    }
}

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

如评论中所述,DLL 必须提供 C 接口(interface)。这意味着,extern "C",没有异常(exception),没有引用等。

编辑:

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

数学.hpp

#ifndef MATH_HPP
#define MATH_HPP

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

#endif

数学.cpp

#include "math.hpp"

int __stdcall math_add(int a, int b)
{
    return a + b;
}

关于c# - 如何在 C++ 中创建 dll 以便在 C# 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8366590/

相关文章:

java - 使用JNI时混淆64位和32位

c# - 如何禁用 MVC 4 模型验证?

c# - 性能——FunctionCall vs Event vs Action vs Delegate

字符串文字的 C++ 引用

c++ - 是否有一个真正有效的示例显示 x86_64 上 Store-Load 重新排序的副作用?

.net - 当非托管依赖项发生冲突时如何使用 2 个第三方 .net 库?

c++ - 编译器警告 C4251 : Problem exporting a class in a *. dll

c# - 在 ASP.NET MVC 模型项目中访问 TenantId

c# - 将二进制定点的 byte[] 转换为浮点值

C++ std::shared_ptr 递增和递减引用计数的竞赛