Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

c++ - Attempted to read or write protected memory. This is often an indication that other memory is corrupt on DLL Import in C#

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. This is Error Screenshot download link.

question from:https://stackoverflow.com/questions/65880690/attempted-to-read-or-write-protected-memory-this-is-often-an-indication-that-ot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...