【发布时间】:2012-05-10 19:56:05
【问题描述】:
我正在尝试做一个基本的 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 中...
谢谢!
【问题讨论】:
-
DLL 文件是 32 位还是 64 位?你的 clr 是 32 位还是 64 位?通常是与您的错误相关的这种类型的不兼容。
-
你这样做是错误的。如果你有一个 ref 类(因此有一个 C++/CLI dll),你根本不需要 DllImport:只需添加对 dll 的引用C# 项目并以“C# 方式”调用函数,即 MathFuncs.Add()
标签: c# c++ visual-studio visual-c++