问题
I am calling unamanaged function from the managed code. But Unamanaged call is not happening.
Managed C# code: (Created a project (Sampletest) from Visual C# -> Console App) Sampletest:
namespace Sampletest
{
class Program
{
const string Dllpath2 = @"C:\Users\apc\source\repos\Sampletest\SampleDll\Debug\SampleDll.dll";
[DllImport(Dllpath2, EntryPoint = @"IsUPSPresent", CallingConvention = CallingConvention.Cdecl)]
public static extern Boolean IsUPSPresent();
static void Main(string[] args)
{
var test = IsUPSPresent();
Console.ReadKey();
}
}
}
Unmanaged C++ code:
(Created a dll project (SampleDll) from Visual C++ -> Windows Desktop -> Dynamic Link Library)
"IsUPSPresent()" definition is there in SampleDll.cpp
#include "stdafx.h"
BOOL IsUPSPresent()
{
BOOL bRetValue = FALSE;
return bRetValue;
}
But when we are making unmanaged call, first it is going to dllmain.cpp file present in unmanaged code.
#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
then it is not going to
BOOL IsUPSPresent() function
and comming back to the managed call at "var test = IsUPSPresent();"
showing the error "Unhandled exception at 0x7705D6C7 (ntdll.dll) in Sampletest.exe: 0xC0000096: Privileged instruction.
Settings i Made:
For C# project,
Debug-> Selected "Enable native code debugging"
And I selected "Debug", "x86"
Please help me to resolve this issue.
回答1:
You have to declare IsUPSPresent
using the __declspec(dllexport)
attribute or use a .def
-file. Also, to overcome C++ name mangling, your definition has to be extern "C"
in C++-code.
extern "C" {
BOOL __declspec(dllexport) IsUPSPresent()
{
BOOL bRetValue = FALSE;
return bRetValue;
}
}
来源:https://stackoverflow.com/questions/52811404/unamanaged-call-is-not-happening-from-the-managed-c-sharp-code