我試圖做一個基本的C++ DLL,以便在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)..任何想法?另外,我複製了C#應用程序的bin文件中的.dll文件...
謝謝!
是DLL文件32還是64位?你的clr是32位還是64位?通常這是與您的錯誤相關的這種不兼容性。 – alegen
你是這樣做的錯誤方式..如果你有一個ref類(因此也是一個C++/CLI DLL),你根本不需要DllImport:只需在C#項目中添加一個對dll的引用,然後調用函數'的C#方式'即MathFuncs.Add() – stijn
@stijin ...感謝很多隊友!:)))多數民衆贊成在正確的答案:)) – user1317277