C ++ DLL导入到C#应用程序中

时间:2012-05-01 08:11:06

标签: c# c++ visual-studio visual-c++

我正在尝试做一个基本的C ++ DLL,以便在C#中使用它..使用以下类:

我的cpp文件

#include "stdafx.h"    
#include "MathFuncsAssembly.h"

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 gcnew DivideByZeroException("b cannot be zero!");
        }

        return a / b;
    }
}

我的头文件

using namespace System;

namespace MathFuncs
{
    public ref class MyMathFuncs
    {
    public:
        static double Add(double a, double b);

        static double Subtract(double a, double b);

        static double Multiply(double a, double b);

        static double Divide(double a, double b);
    };
}

在我调用库的C#应用​​程序中

[DllImport("MathFuncsAssembly.dll")]
public static extern double Add(double a, double b);

static void Main(string[] args)
{
   Console.WriteLine(Add(10.0, 11.0));
   Console.ReadLine();
}

(Add(10.0,11.0))部分发生异常。抛出以下异常: 尝试加载格式不正确的程序。 (HRESULT的例外情况:0x8007000B)..有什么想法吗?另外,我将.dll文件复制到c#应用程序的bin中。

谢谢!

3 个答案:

答案 0 :(得分:1)

如果你有一个ref类(因此有一个C ++ / CLI dll),你根本不需要DllImport:只需在C#项目中添加对dll的引用,并调用函数'C#way'即{ {1}}(请注意,您仍然需要确保平台匹配,并且CLI dll所依赖的所有本机dll都在路径中)

答案 1 :(得分:0)

通常,当您尝试将x32 DLL与x64程序一起使用时,或者反之亦然。

答案 2 :(得分:0)

“不正确的格式”异常总是意味着您正在加载为不同平台编译的模块,即32位与64位。确保您的DLL和C#应用程序是针对同一平台编译的。如果为“任何平台”设置了C#,请明确选择您的DLL所用的那个。