Reputation: 113
I am trying to do a basic C++ DLL in order to use it in C#.. the following classes are used:
My cpp file
#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;
}
}
My header file
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);
};
}
and in my C# application where I am invoking the library
[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();
}
An exception occurs at the (Add(10.0,11.0)) part.. The following exception is being thrown: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B).. Any Ideas? Also, i copied the .dll file in the bin of the c# application...
thanks!
Upvotes: 0
Views: 552
Reputation: 35901
If you have a ref class (and hence a C++/CLI dll), you don't need DllImport at all: just add a reference to the dll in the C# project and call the functions 'the C# way' i.e. MathFuncs.Add()
(note you still need to make sure the platform matches, and that all native dlls the CLI dll depends on are in the path)
Upvotes: 1
Reputation: 7961
"Incorrect format" exceptions always mean that you're loading a module compiled for a different platform i.e. 32 vs 64 bit. Make sure your DLL and your C# app are compiled for the same platform. If C# is set for "Any platform" select explicitly the one that your DLL is for.
Upvotes: 0
Reputation: 500
Usually this happens when you are trying to use a x32 DLL with a x64 program or viceversa.
Upvotes: 0