创建C++ DLL然后在C#中使用它

Maj*_*jor 4 c# c++ dll

好的我正在尝试创建一个C++ DLL,然后我可以在ac#App中调用和引用它.我已经使用了很多指南制作了一个简单的dll,但是当我尝试在C#应用程序中引用它时,我得到了错误

无法加载DLL"SDES.dll":找不到指定的模块.

该程序的代码如下(跟我一起,我将包含所有文件)

//These are the DLL Files.

#ifndef TestDLL_H
#define TestDLL_H

    extern "C"
    {
        // Returns a + b
        __declspec(dllexport) double Add(double a, double b);

        // Returns a - b
        __declspec(dllexport) double Subtract(double a, double b);

        // Returns a * b
        __declspec(dllexport) double Multiply(double a, double b);

        // Returns a / b
        // Throws DivideByZeroException if b is 0
        __declspec(dllexport) double Divide(double a, double b);
    }

#endif

//.cpp
#include "test.h"

#include <stdexcept>

using namespace std;

    extern double __cdecl Add(double a, double b)
    {
        return a + b;
    }

    extern double __cdecl Subtract(double a, double b)
    {
        return a - b;
    }

    extern double __cdecl Multiply(double a, double b)
    {
        return a * b;
    }

    extern double __cdecl Divide(double a, double b)
    {
        if (b == 0)
        {
            throw new invalid_argument("b cannot be zero!");
        }

        return a / b;
    }

//C# Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("SDES.dll")]
        public static extern double Add(double a, double b);
        static void Main(string[] args)
        {
            Add(1, 2); //Error here...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人都知道我的程序中可能缺少什么?如果我错过了一些代码或者您有任何问题,请告诉我.

Sim*_*mon 5

下载Dependecy Walker并打开你的SDES.dll.检查是否可以加载所有相关DLL.如果您发现缺少依赖性,也将该dll放在目标目录中.

您使用的是64位系统吗?如果是,则应将C#和C++定位到相同的体系结构(32位或64位).

我刚刚测试了你的功能,结果很好.

    [DllImport("Native_CPP.dll", CallingConvention=CallingConvention.Cdecl)]
    public static extern double Add(double a, double b); 

    static void Main(string[] args)
    {
        Console.WriteLine(Add(1.0, 3.0));

        Console.ReadLine();
    }
Run Code Online (Sandbox Code Playgroud)

输出:

4
Run Code Online (Sandbox Code Playgroud)

这就是我在Visual Studio 2010中所做的:

  • 创建一个新的解决方案
  • 创建一个新的C#项目
  • 创建一个新的C++ - Dll项目(没有MFC和其他东西)
  • 复制粘贴标题和cpp文件
  • 构建C++ - Dll
  • 将DLL复制到C#项目的Debug/Release(取决于您使用的是什么)目录(通常分别为"Solution/CSharpProjectName/bin/Debug /"或"Solution/CSharpProjectName/bin/Release /")
  • 将此P/Invoke签名添加到C#文件:

    [DllImport("Native_CPP.dll", CallingConvention=CallingConvention.Cdecl)] public static extern double Add(double a, double b);

    注意:我必须传递参数CallingConvention.Cdecl,否则我得到一个例外.

  • 运行C#-Project,如上所示

PS:我没有必要设置架构.它刚刚起作用.(我正在使用带有64位操作系统的x64机器.)