Intermittent Access Violation when using C# to access C++ DLL

▼魔方 西西 提交于 2020-01-05 07:56:29

问题


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.



来源:https://stackoverflow.com/questions/30121129/intermittent-access-violation-when-using-c-sharp-to-access-c-dll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!