Search code examples
c++-cliwrapper

System.AccessViolationException: 'Attempted to read or write protected memory. (Making a wrapper for a c++ lib)


My constructor is as next

 ScaperEngine::ScaperEngine(GrabberType grabberType, bool timing) {
    switch (grabberType)
    {
    case GrabberType::DepthSenseGrabber:
        this->interface = new pcl::DepthSenseGrabber("");
        break;
    default:
        throw new std::exception("Grabber type wasn't chosen correctly");
        break;
    }
    executionPipeline = new ExecutionPipeline();
    executionPipeline->setTiming(timing);
}

And then I have some code like:

    void ScaperEngine::StartPipeline()
{
    IPCLNormalCalculator* normalCalculator = new PCLNormalCalculator(normalCalcMaxDepthChangeFactor, normalSmoothingSize);
    executionPipeline->SetPCLNormalCalculator(normalCalculator);

The most strange thing is that the constructor is building executionPipeline in the right way putting its place in memory in 0x0000020ef385e830, but when my c# managed code calls StartPipeline the executionPipeline address changed to 0xcdcdcdcdcdcdcdcd and in Quick Watch the following text appears for its variables <Unable to read memory>.

Please anyone has a clue whats going on?

With many thanks.


Solution

  • The 0xcdcdcdcdcdcdcdcd you are seeing is a special feature of the Visual Studio debugger that represents uninitialized heap memory. A more comprehensive list of codes are available from this StackOverflow question. In brief, it seems as though your C# code is calling StartPipeline() on an invalid object. This could happen, for example, if the pointer is altered to point to a random location in heap memory. Make your C# code (and the runtime) is properly storing the pointer to the ScraperEngine object and not corrupting it along the way.