托管C#代码未发生非托管调用
我正在从托管代码中调用非托管函数.但是未托管的呼叫不会发生.
I am calling unamanaged function from the managed code. But Unamanaged call is not happening.
托管的C#代码: (通过Visual C#->控制台应用程序创建了一个项目(最简单)) 样品测试:
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();
}
}
}
非托管C ++代码:
(从Visual C ++-> Windows桌面->动态链接库创建了一个dll项目(SampleDll)
(Created a dll project (SampleDll) from Visual C++ -> Windows Desktop -> Dynamic Link Library)
在SampleDll.cpp中有"IsUPSPresent()"定义
"IsUPSPresent()" definition is there in SampleDll.cpp
#include "stdafx.h"
BOOL IsUPSPresent()
{
BOOL bRetValue = FALSE;
return bRetValue;
}
但是,当我们进行非托管调用时,首先要转到非托管代码中存在的dllmain.cpp文件.
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;
}
那么它就不会
BOOL IsUPSPresent()函数
BOOL IsUPSPresent() function
并返回到"var test = IsUPSPresent();"处的托管调用.
and comming back to the managed call at "var test = IsUPSPresent();"
显示错误"Sampletest.exe中的0x7705D6C7(ntdll.dll)出现未处理的异常:0xC0000096:特权指令.
showing the error "Unhandled exception at 0x7705D6C7 (ntdll.dll) in Sampletest.exe: 0xC0000096: Privileged instruction.
我所做的设置:
对于C#项目,
Debug->选择启用本机代码调试"
Debug-> Selected "Enable native code debugging"
然后我选择了调试","x86"
And I selected "Debug", "x86"
请帮助我解决此问题.
您必须使用__declspec(dllexport)
属性声明IsUPSPresent
或使用.def
文件.另外,要克服C ++名称修饰的问题,您的定义必须在C ++代码中为extern "C"
.
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;
}
}