Runtime exception Invalid access to memory location while using a c++ dll

0

I have a C# program that uses a C++ dll and sometimes I get the exception "Invalid access to memory location. (Exception from HRESULT: 0x800703E6)" (I mentioned in the code where). When I run it using VisualStudio it doesn't fail but when I use the exe file it sometimes crashes and sometimes works. Can someone help me figure out why?

The C++ code:

extern "C" __declspec(dllexport) int SomeFunction(char* file, char* output)
{
    string filePath(file, strlen(file));

    string message = "";
    string buff;
    ifstream fileStream(filePath);

    while (std::getline(fileStream, buff))
    {
        message += (buff);
    }

    if (message != "")
    {
        string retString;
        retString.clear();

        /* Do something to retString */

        if(retString.length() == 768)
        {
            sprintf(output, "%s", retString.c_str());
            return 1;
        }
        else
        {
            return 0;
        }
    }
    else
    {
        return 0;
    }
}

The C# code:

 [DllImport("CPPWrapper.dll", EntryPoint = "SomeFunction", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
  public static extern int SomeFunction(IntPtr filePath, IntPtr output);

     private ResultValue ScanFoldersFiles(DirectoryInfo dir)
    {
        foreach (FileInfo file in dir.GetFiles())
        {
            string fileName = file.Name;
            string filePath = file.FullName;

            IntPtr filePathPtr = Marshal.StringToHGlobalAnsi(filePath);
            IntPtr result = Marshal.AllocHGlobal(768);

            try
            {
                if (SomeFunction(filePathPtr, result) != 0)
                {
                    string retString = Marshal.PtrToStringAnsi(result, 768);

                    FileAndString l_file = new FileAndString(fileName, retString);
                    m_FilesInFolderList.Add(l_file);
                }
                else
                {
                    Marshal.FreeHGlobal(filePathPtr);
                    Marshal.FreeHGlobal(result);
                    return ResultValue.FAILED;
                }
            }
            catch (Exception ex)
            {
                Marshal.FreeHGlobal(filePathPtr);
                Marshal.FreeHGlobal(result);
                return ResultValue.FAILED;
            }

            Marshal.FreeHGlobal(filePathPtr);
            Marshal.FreeHGlobal(result); // This is where it fails
        }

        return ResultValue.SUCCESS;
    }
c#
c++
asked on Stack Overflow Feb 26, 2018 by Shani.M

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0