Intermittent Access Violation when using C# to acc

2019-08-12 08:13发布

问题:

I'm linking from c# to a quite complex c++ dll. I need to create a lot of dllexport funtions so I can use the dll in c#. To get started, I added a .cpp file and created a simple test function:

c++:

extern "C" __declspec(dllexport) int32_t Test(){
    return 10;
}

c#:

[STAThread]
static void Main()
{
    Console.WriteLine(Test());
}

[DllImport("Test.dll", EntryPoint = "Test", CallingConvention = CallingConvention.Cdecl,ExactSpelling = true)]
public static extern Int32 Test();

This test works perfectly 90% of the time and then suddenly....

The program '[4712] Test.vshost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.

Everything seems fine, no idea what causes it or even how to begin to track down the problem. It's weird that it is so intermittent. I'm not a c++ programmer really so I've no idea what might cause this behaviour, or even how to debug and find the problem.

Hope some kind soul can help.

回答1:

This

SetLastError = true

is useless unless you are using Windows API.

And set the

CallingConvention = CallingConvention.Cdecl

like

[DllImport("Test.dll", EntryPoint = "Test", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]

Note that there is code other than your method that could be executed. A DLL can (and often does) have a DllMain method. Often in this method "global" variables of the dll are initialized, and so are methods that must be called a single time. This method is normally called at least twice: DLL_PROCESS_ATTACH when the dll is loaded and DLL_PROCESS_DETACH when the process ends/the dll is unloaded.



标签: c# c++ dll