I have a C++ developed DLL which I want to load and call a function on C# but I got Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Error. My C++ code is like below:
#include "EvenOdd.h"
extern "C"
{
__declspec(dllexport) std::string CheckEvenOdd(const int iNum)
{
std::string strRes = "NULL";
if(iNum%2 == 0)
{
strRes = "The given number is Even";
}
else
{
strRes = "The given number is Odd";
}
return strRes;
}
}
My C# code is like Bellow:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace C_Sharp_DLL_Test1
{
class Program
{
[DllImport("C:\\Users\\saja\\Downloads\\LoadLibrary\\GetEvenOdd\\Debug\\GetEvenOdd.dll", CallingConvention=CallingConvention.StdCall)]
[MethodImpl(MethodImplOptions.ForwardRef)]
static extern string CheckEvenOdd(int num);
static void Main(string[] args)
{
string s = CheckEvenOdd(23);
Console.WriteLine(s);
Console.ReadLine();
}
}
}
That error occurs on string s = CheckEvenOdd(23);
line. I test this code in Windows 10, Windows 7, Visual Studio 2019, Visual Studio 2010, and the debug profile on Visual Studio is on X86 CPU. This is DLL download link.