Click here to Skip to main content
15,887,340 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a c# code that calls a dll (cpp build) and writes a text file (of 12 MB size) of txt file to a variable by calling a cpp dll

Getting following errors :

{"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."}

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.


What I have tried:

c# code :
// this is the code to call the dll (cpp build)

<pre> private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                System.Threading.ThreadStart starter = delegate { CallTheNumerOfTimesEx(1, 98600, "Thread1"); }; // 100000 95600
                System.Threading.Thread thread = new System.Threading.Thread(starter);
                thread.Start();

                thread.Join();

                string outputFile = @"D:\SampleJFile.txt";
                if (File.Exists(outputFile))
                    File.Delete(outputFile);
                string loging = someVariable // someVariable contains string size of 10 MB//

                using (StreamWriter writer = new StreamWriter(outputFile))
                    writer.WriteLine(toLog);
                obj.Information("Asdf", loging , "asdf"); // This is the (cpp build) dll function

            }
            catch (Exception ex)
            {
                tracelog.Error(ex);
            }
            MessageBox.Show("");

        }


cpp function that writes the received data :


void Trace::Information (String^ category, String^ messageText, String ^stackTrace)
{
    String ^oldCategory = traceMessage->category;
    TM->eventType = KTEventType::Information;
    TM->category = category;
    TM->errorCode = 0;
    TM->messageText = messageText;
    this->TM->timeStamp = DateTime::Now.ToString ("yyyy-MM-dd HH:mm:ss.fff");

    if (stackTrace == nullptr)
    {
        System::Diagnostics::StackTrace ^st = gcnew System::Diagnostics::StackTrace ();
        TM->stackTrace = st->ToString ();
    }
    else 
        TM->stackTrace = stackTrace;

    LogMessage (TM);
    TM->stackTrace = nullptr;
    TM->category = oldCategory;
};





the given variables are declared as follows

private:
     TraceMessage ^TM;

struct EXPORT_CLASS TraceMessage		
			{
public:
KTEventType	eventType;		
LPCWSTR		category;			
KTWSTRING		timeStamp;			
LPCWSTR		machineName;		
LPCWSTR		applicationName;	
LPCWSTR		userName;			
LPCWSTR		threadID;			
long		errorCode;			
LPCWSTR		messageText;		
LPCWSTR		stackTrace;			
LPCWSTR		errorSource;		
byte		logLevel;
}

void GenericLogger::LogMessage(ILogMessage^ logMessage)
{
	bool sharedMemoryLockHeld = false;
	try
	{	
		// Perform necessary validations
		// Validate the custom log message passed
		if(logMessage == nullptr)
		{
			throw gcnew ArgumentException("Custom log message passed to LogMessage method is null.");
		}
		
		// Validate the message id returned by the custom log message
		long messageId = logMessage->MessageId;
		
		// Ensure that the message id specified is non-negative
		if(messageId < 0)
		{
			throw gcnew ApplicationException("All custom message Ids must be positive integers. Please specify another message id for this custom log message.");
		}

		// Ensure that the message id specified is not a reserved message id
		// for TraceMessage message types
		if(messageId == 0)
		{
			throw gcnew ApplicationException("The message id '0' is reserved for TraceMessage message types. Please specify another message id for this custom log message.");
		}

		// Initialize the shared memory writer
		Init();
		
		// Use the BinaryFormatter to serialize the custom message
		// to the memory stream
		MemoryStream^ pMemStream = gcnew MemoryStream();
		BinaryFormatter^ pFormatter = gcnew BinaryFormatter();
		pFormatter->Serialize(pMemStream, logMessage);

		// Get the serialized byte array from the memory stream
		array<unsigned char>^ arrSerializedBytes = 
							pMemStream->GetBuffer();
		
		if(arrSerializedBytes != nullptr)
		{
			// Get the length of the serialized byte array
			int customMessageLength =  arrSerializedBytes->Length;

			if(customMessageLength > 0)
			{
				// The total message size =  
				// [Field that stores the length of the message (4 bytes)] + 
				// [Field that stores the message type (Trace/Custom/UnmanagedCustom (4 bytes))] +
				// [Field that stores the message Id (4 bytes)] +
				// [ Actual length of the serialized custom message].
				int totalMessageSize = customMessageLength + 12;
				
				// Begin writing into the shared memory. This actually procures the 
				// necessary locks for writing into shared memory
				m_pShmWriter->BeginWrite(totalMessageSize);
				sharedMemoryLockHeld = true;

				// Write the message type indicating that it is a 
				// custom message
				m_pShmWriter->AddLong((long)LogType::Custom);
				
				// Write the message id associated with the message
				m_pShmWriter->AddLong(messageId);

				// Write the serialized byte array to the shared memory
				m_pShmWriter->Write((array<system::byte> ^)arrSerializedBytes);
			}
		}
		
	}// end try
	catch(Exception^ pEx)
	{
		// Rethrow the exception
		Trace::WriteLine(pEx->Message);
		
	}
	finally
	{
		if(sharedMemoryLockHeld)
		{
			//Release all acquired locks in shared memory.
			m_pShmWriter->EndWrite();
			sharedMemoryLockHeld = false;
		}
	}



Could anyone suggest to fix the issue
Posted
Updated 21-Dec-17 19:10pm
v3
Comments
Jochen Arndt 21-Dec-17 7:32am    
It is not clear from your code snippets where the access violation occurs and when and how the functions are called (e.g. what does LogMessage() do?).

Most of the TraceMessage struct members are pointers (LPCWSTR). These will be only valid while the assigned objects exist and are therefore a possible source of your problem. If so, they should be changed to string objects.
Greek Varak 21-Dec-17 8:04am    
Thanks for your reply yaaar... i am new to C++... Actually it breaks at
obj.Information("Asdf", loging , "asdf"); with access violation error.
it works fine when we have a samplejfile of 9.99 mb . When we pass 10 mb of text file to the cpp dll it fails... I will try with string objects ... and log message is a generic function.

Jochen Arndt 21-Dec-17 8:12am    
obj.Information("Asdf", loging , "asdf"); with access violation error.

Start there. What is the value of 'loging'? Is 'obj' valid? Inspect the code of the Information function and the access to 'loging'.

Please don't post such code blocks as comments. They are nearly unreadable. You can use the green 'Improve question' link to add such to your question. But post only code that is related to the question (long questions are also hard to read and many who might be able to help will skip them).
Greek Varak 21-Dec-17 8:47am    
Sorry jochen, i had made it improve question as you said ... Actually when i try to debu through obj.information by pressing Function F11 doesnt debug through the dll... Thats where i struck ....
Jochen Arndt 21-Dec-17 9:07am    
No problem.

But it is still unclear:

KTTrace::LogMessage(TraceMessage ^TM)

That does not match

GenericLogger::LogMessage(ILogMessage^ logMessage)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900