Access Violation Exception/Crash from C++ callback to C# function

后端 未结 4 457
时光说笑
时光说笑 2021-01-12 21:22

So I have a native 3rd party C++ code base I am working with (.lib and .hpp files) that I used to build a wrapper in C++/CLI for eventual use in C#.

I\'ve run into

4条回答
  •  醉酒成梦
    2021-01-12 22:20

    I'm not sure what your are trying to achieve.

    A few points:

    1) The garbage collector is more aggressive in release mode so with bad ownership the behaviour you describe is not uncommon.

    2) I don't understands what the below code is trying to do?

    IntPtr ip2 = GCHandle.ToIntPtr(GCHandle.Alloc(new DataLoggerWrap(pData)));
    DataLoggerWrap dlw = (DataLoggerWrap)GCHandle.FromIntPtr(ip2).Target;
    

    You use GCHandle.Alloc to lock an instance of DataLoggerWrap in memory, but then you never pass it out to unmanaged - so why do you lock it? You also never free it?

    The second line then grabs back a reference - why the circular path? why the reference - you never use it?

    3) You set the IntPtrs to null - why? - this will have no effect outside of the function scope.

    4) You need to know what the contract of the callback is. Who owns pData the callback or the calling function?

提交回复
热议问题