views:

171

answers:

1

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

+2  A: 

Based on the description of your code "the class is managed" it doesn't sound to me like memory being moved around. If reader is 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 reader class is mixed mode C++ (managed plus unmanaged code).

Some things to lookout for in that case

  • Is your C++ class allocating a buffer on the c runtime heap and trying to pass it to managed code?
  • Is your C++ 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:

  • If you have unmanaged C++ code are you null-ing all of your buffer allocations? An arbitrary array of bytes malloc-ed from the c-runtime heap is not nulled out the way a gcnew array<Byte>(256) would be. (Recently had a big DOH moment after a few minutes trying to figure out why free was blowing up in my face when I thought for sure the buffer should be NULL)
dkackman