Hello,
This question is 2 years old, but the answer is never old. I am answering the question with absolute correct answer. Other developers may benefit from my answer. It was posted three time because the web site stated it failed to post 2 times by mistake.
The problem relies on how you import the function in your native C++ code. You can not do the way you are doing now. If you use the following C++ code to import your function, the the name of the export function must be mangled, you must come up with exact mangled name as Visual C++ does. I have removed my article link, the article is well-written though.
#pragma once
#define DllImport __declspec(dllimport)
namespace AddDll
{
class MyAddDll
{
public:
static DllImport double Add(double a, double b);
};
}
Insead of using namespace and class, you should simply use extern "C" statement like the one shown below.
extern "C"
{
double Add(double a, double b);
}
Since the default calling convention in C++ is __cdecl, you will also need to change the calling convention in the C# code, remember that name of a __stdcall of a export function needs to be mangled as well, in this case, it is Add@16, you don't want to do mangled name, so, please just use __cdecl, it is much simpler.
using System;
using System.Collections.Generic;
using System.Text;
using RGiesecke.DllExport;
namespace AddDll
{
class MyAddDll
{
[DllExport("Add", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
public static double Add(double a, double b)
{
return a + b;
}
}
}