C++ DLL imported into a C# application

0

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!

c#
c++
visual-studio
visual-c++
asked on Stack Overflow May 1, 2012 by user1317277

3 Answers

1

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)

answered on Stack Overflow May 1, 2012 by stijn
0

Usually this happens when you are trying to use a x32 DLL with a x64 program or viceversa.

answered on Stack Overflow May 1, 2012 by Stefan Manciu
0

"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.

answered on Stack Overflow May 1, 2012 by Maciej

User contributions licensed under CC BY-SA 3.0