I am trying to learn P/Invoke, so I created a simple dll in C++
KingFucs.h:
namespace KingFuncs
{
class KingFuncs
{
public:
static __declspec(dllexport) int GiveMeNumber(int i);
};
}
KingFuns.cpp:
#include "KingFuncs.h"
#include <stdexcept>
using namespace std;
namespace KingFuncs
{
int KingFuncs::GiveMeNumber(int i)
{
return i;
}
}
So it does compile, then I copied this dll into my WPF’s debug folder, with code:
[DllImport("KingFuncDll.dll", EntryPoint = "GiveMeNumber", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int GiveMeNumber(
int i
);
And calling it in button click:
private void Button_Click(object sender, RoutedEventArgs e)
{
int num = GiveMeNumber(123);
}
But it gives me exception:
Unable to find an entry point named ‘GiveMeNumber’ in DLL
‘KingFuncDll.dll’.
Really…. what have I done wrong… It obviously able to find the DLL, otherwise would be another exception. But my method name is exactly the same…. I can’t think of other reason.
You need to use
extern "C"when you export your function so that you suppress C++ name mangling. And you also should not try to p/invoke to members of a class. Use free functions instead:On the managed side your
DllImportattribute is all wrong. Don’t useSetLastErrorwhich is for Win32 APIs only. Don’t bother settingCharSetif there are not text parameters. No need forExactSpelling. And the calling convention is presumablyCdecl.