Reputation: 1186
So I have a DLL that I made with C++ and I am using it in C#. The problem is that I use a function pointer in C++, so I made a delegate. The hole program works but after it finishes I got a message box stating that the value of ESP was not saved for the function.
My code: C++ The DLL
typedef void (*FUNCTION_TYPE)(bool);
extern "C"
{
DLL void prim(int a, FUNCTION_TYPE myF)
{
if(a < 2)
{
myF(false);
return;
}
for (int i = 2; i < a; i++)
{
if (a % i == 0)
{
myF(false);
return;
}
}
myF(true);
}
};
My C# code (calling the dll):
delegate void SOME_FUNCTION(bool isFine);
[DllImport("DLLs")]
private static extern void prim(int n, SOME_FUNCTION afisare);
static void afisare(bool isFine)
{
if (isFine == true)
Console.WriteLine("Da, e prim");
else
Console.WriteLine("Nu, nu e prim");
}
static void Main(string[] args)
{
SOME_FUNCTION myAfis = afisare;
prim(17, myAfis);
}
Upvotes: 2
Views: 256
Reputation: 613311
You have a calling convention mismatch. The C++ function pointer type uses cdecl
. The managed code assumes stdcall
. Fix it like this:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void SOME_FUNCTION(bool isFine);
Alternatively you could change the calling convention in the C++ code to stdcall
:
typedef void (__stdcall *FUNCTION_TYPE)(bool);
But make sure you do only one of these and not both!
Upvotes: 2