I have a native (unmanaged) .dll written in C++ that is to be called from a managed process (a C# program). When debugging the dll the problem I have has shown to be that when I create an object in the dll with the new
keyword I get a System Access Violation Exception. This only shows up when calling the dll from a managed process, not when I am calling it from another native program.
The code is something similar to this:
// Native.dll file
MyClass myInstance; // global variable (and does need to be so)
__declspec(dllexport) uint8_t _stdcall NativeFunction(){
myInstance = new MyClass(); // <-- this causes Access Violation Exception
}
and the C# code:
using System.Runtime.Interopservices;
// Loading the dll
[DllImport("Native.dll",CallingConvention = CallingConvention.StdCall)]
private extern static byte NativeFunction();
class TestClass{
byte returnVal = NativeFunction(); //<-- exception in managed context
}
I know this has something to do with the native process trying to allocate memory outside allowed memory-space. It only happens when memory is allocated with new
(at least in this project) which I unfortunately do need to use. My question is: Does anyone know why this is causing the exception and how to avoid it?