Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to do memory copy by using memcpy_s from a int* pointer, but I got "AccessViolationException:Attempted to read or write protected memory.

here is my code:

the exception is thrown in the line memcpy_s, I think the problem may be I misuse the *DataPoint??

C++
void CopyMemoryDataToNewArray(int *DataPointer, int DataSize)
{
   array<System::Byte>^ ByteArray = gcnew array<System::Byte>(DataSize);
   pin_ptr<Byte> desPointer = &ByteArray[ByteArray->GetLowerBound(0)];

   //exception is thrown in the line: Attempted to read or write protected memory. 
   memcpy_s(desPointer, sizeof(ByteArray), DataPointer, sizeof(ByteArray));
}

int main(array<System::String ^> ^args)
{
   System::String ^ImgFileName = "SampleImage2.jpg";
   //get the img byte array
   array<System::Byte>^ DataArray = ImageToByteArray(ImgFileName);
   //try to get the pointer of img address
   int* _pointer = (int*)DataArray[0];
   CopyMemoryDataToNewArray(_pointer, DataArray::Length);
}  
Posted
Updated 8-Nov-14 12:06pm
v3

Your line:
C++
int* _pointer = (int*)DataArray[0];

But you should use this instead:
C++
int* _pointer = (int*)&DataArray[0];
 
Share this answer
 
Comments
Member 9857514 8-Nov-14 14:46pm    
Hi, I changed the line and get compiler error: "error C2440: 'type cast' : cannot convert from 'cli::interior_ptr<type>' to 'int *'"
1) sizeof(ByteArray) should be ByteArray->Length.
2) You cannot cast mnaged types to unmanaged one like that. You have to uses pin_ptr or something like that.
3) Do you really have to mix managed and unmanaged code? If so, you have to learn it and if not, better to use either only managed or only unmanaged code.

By the way, transistion between these 2 mode have some overhead and you need to be aware of that if you are doing image manipulations.

MSDN has information on how to use pin_ptr and other stuff.

You might also want to consider P/Invoke.
 
Share this answer
 

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