简体   繁体   中英

AccessViolationException If I declare the variable as Public Members, instead of local variable

I have 2 interop data structure as private member in a class,

public class RunInterop
{

        private AlphaShapeCg _alphaHandler;
        private DoubleCgList alphaLevels;
        private FaceCgList faceCgList;
    public RunInterop()
        {
            faceCgList =new FaceCgList();
            alphaLevels = new DoubleCgList();
            Interop_Init(ref _alphaHandler, ref faceCgList, ref alphaLevels);

           Interop_Run(ref _alphaHandler);
        }
}

The problem now, is that I will get an System.AccessViolationException at Interop_Run line.

However, if I rewrite my code in the following manner:

public class RunInterop
{
   private AlphaShapeCg _alphaHandler;
    public RunInterop()
        {
           var faceCgList =new FaceCgList();
           var alphaLevels = new DoubleCgList();
            Interop_Init(ref _alphaHandler, ref faceCgList, ref alphaLevels);

           Interop_Run(ref _alphaHandler);
        }
}

Then I wouldn't have any problem. Any idea why this is the case?

Edit: What is really puzzling is that, why, if I declare both the faceCgList and alphaLevels as local variables, the problem would just go away?

What happens in Interop_Init and Interop_Run ? You are passing the two members alphaLevels and faceCgList into Interop_Init - maybe it is keeping some reference to them that are used again when calling Interop_Run , at which point it might appear to be accessing the private member of a different class?

Edit: just an idea :)

public class RunInterop
{
    private AlphaShapeCg _alphaHandler;
    private DoubleCgList _alphaLevels;
    private FaceCgList _faceCgList;

    public RunInterop()
    {
        AlphaShapeCg faceCgList = new FaceCgList();
        DoubleCgList alphaLevels = new DoubleCgList();
        Interop_Init(ref _alphaHandler, ref faceCgList, ref alphaLevels);
        Interop_Run(ref _alphaHandler);
        _alphaLevels = alphaLevels;
        _faceCgList = faceCgList;
    }
}

Edit: I found this link explaining how the managed / unmanaged marshaling works in Mono - I'm struggling to find a similar informative article for Microsoft's dotNET Framework, but my guess would be that it should work in a similar way. Here's one quote from the article:

Additionally, if (a) the structure is located on the stack, and (b) the structure contains only blittable types, then if you pass a structure to an unmanaged function by-reference, the structure will be passed directly to the unmanaged function, without an intermediate unmanaged memory copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM