Cannot call DLL import entry, C# -> C++, EntryPointNotFoundException

微笑、不失礼 提交于 2019-12-02 22:17:06

问题


I'm trying to call from C# a function in a custom DLL written in C++. However I'm getting the warning during code analysis and the error at runtime:

Warning: CA1400 : Microsoft.Interoperability : Correct the declaration of 'SafeNativeMethods.SetHook()' so that it correctly points to an existing entry point in 'wi.dll'. The unmanaged entry point name currently linked to is SetHook.

Error: System.EntryPointNotFoundException was unhandled. Unable to find an entry point named 'SetHook' in DLL 'wi.dll'.

Both projects wi.dll and C# exe has been compiled in to the same DEBUG folder, both files reside here. There is only one file with the name wi.dll in the whole file system.

C++ function definition looks like:

#define WI_API __declspec(dllexport)
bool WI_API SetHook();

I can see exported function using Dependency Walker:

as decorated: bool SetHook(void)
as undecorated: ?SetHook@@YA_NXZ

C# DLL import looks like (I've defined these lines using CLRInsideOut from MSDN magazine):

[DllImport("wi.dll", EntryPoint = "SetHook", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool SetHook();

I've tried without EntryPoint and CallingConvention definitions as well.

Both projects are 32-bits, I'm using W7 64 bits, VS 2010 RC.

I believe that I simply have overlooked something....

Thanks in advance.


回答1:


Well, you know the entry point name, use the EntryPoint = "?SetHook@@YA_NXZ" property in the [DllImport] attribute. Or put extern "C" before the declaration in your C++ code so the name doesn't get mangled.

[DllImport("wi.dll", EntryPoint = "?SetHook@@YA_NXZ", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool SetHook();



回答2:


CallingConvention.Cdecl means C not C++, so when you have a function with a C++ decorated name, you need to use the decorated name as your EntryPoint or use Extern "C" in The C++ code declaration to turn off C++ name decoration.



来源:https://stackoverflow.com/questions/2465243/cannot-call-dll-import-entry-c-sharp-c-entrypointnotfoundexception

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