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

后端 未结 4 420
时光说笑
时光说笑 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:06

    I'm with @jdehaan, except CallingConvetion.StdCall could be the answer, especially when the 3rd party lib is written in BC++, for example.

    0 讨论(0)
  • 2021-01-12 22:11

    This doesn't directly answer your question, but it may lead you in the right direction as far as debug mode okay vs. release mode not okay:

    Since the debugger adds a lot of record-keeping information to the stack, generally padding out the size and layout of my program in memory, I was “getting lucky” in debug mode by scribbling over 912 bytes of memory that weren’t very important. Without the debugger, though, I was scribbling on top of rather important things, eventually walking outside of my own memory space, causing Interop to delete memory it didn’t own.

    What is the definition of DataLoggerWrap? A char field may be too small for the data you are receiving.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-01-12 22:22

    I think the stack got crushed because of mismatching calling conventions: try out to put the attribute

     [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    

    on the callback delegate declaration.

    0 讨论(0)
提交回复
热议问题