I am wrapping up a class which reading a custom binary data file and makes the data available to a .net/c# class
However a couple of lines down the code, i start getting the memory access violation error which i believe is due to the GC moving memory around, the class is managed
Here’s the calling code in C# – reader is mixed code ( managed wrapper methods on old unmanaged code )
if ( ! reader.OpenFile(...) )
return ;
foreach(string fieldName in fields)
{
int colIndex = reader.GetColIndex( fieldName );
int colType = reader.GetColType( colIndex ); // error is raised here on 2nd iteration
}
for ( int r = 0 ; r < reader.NumFields(); r++ )
{
foreach(string fieldName in fields)
{
int colIndex = reader.GetColIndex( fieldName );
int colType = reader.GetColType( colIndex ); // error is raised here on 2nd iteration
switch ( colType )
{
case 0 : // INT
processField( r, fieldName, reader.GetInt(r,colIndex) );
break ;
....
}
}
}
....
Reader has an old unmanaged class instance reference which holds the binary data in memory
AND It’s a pointer type since a managed class cannot hold an unmanaged type
i’ve looked at interior_ptr, pin_ptr but they give an error c3160 cannot be in a managed class
Any workaround ? BTW, this is my 1st C++ program in a very long time !
UPDATE :
updated the Q, again the above is the calling code and reader is mixed ( managed + old unmanaged code )
& yes the arguments are all valid
Based on the description of your code “the class is managed” it doesn’t sound to me like memory being moved around. If
readeris a managed class and the consumer is a managed class, all of their allocations are on the managed heap, and they don’t call any unmanaged APIs, pinning isn’t necessary.It sounds more like your
readerclass is mixed mode C++ (managed plus unmanaged code).Some things to lookout for in that case
on the c runtime heap and trying to
pass it to managed code?
class allocating a buffer on the
managed heap and trying to pass it to
unmanaged code (this is where you need pinning)?
and this one which nailed me just recently:
gcnew array<Byte>(256)would be. (Recently had a big DOH moment after a few minutes trying to figure out whyfreewas blowing up in my face when I thought for sure the buffer should beNULL)