DLL的设计和使用

目的:VS2019生成DLL,codeblock GCC调用DLL。

一 . 设计生成DLL,使用VS2019

step1:先使用VS2019自动生成MFC dll的工程;

Step2:在dllmain.cpp中添加如下代码:
#include <windows.h>

#define EOF (-1)

#ifdef __cplusplus    // If used by C++ code, 
extern "C" {          // we need to export the C interface
#endif

    __declspec(dllexport) int __cdecl myPuts(char * lpszMsg)
    {
        DWORD cchWritten;
        HANDLE hConout;
        BOOL fRet;

        // Get a handle to the console output device.
        MessageBox(NULL,TEXT("this is dll message!"), TEXT("hellO"), MB_ICONASTERISK);

        hConout = CreateFileW(L"CONOUT$",
            GENERIC_WRITE,
            FILE_SHARE_WRITE,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

        if (INVALID_HANDLE_VALUE == hConout)
            return EOF;

        // Write a null-terminated string to the console output device.

        while (*lpszMsg != L'\0')
        {
            fRet = WriteConsole(hConout, lpszMsg, 1, &cchWritten, NULL);
            if ((FALSE == fRet) || (1 != cchWritten))
                return EOF;
            lpszMsg++;
        }
        return 1;
    }

#ifdef __cplusplus
}
#endif

二. 使用CodebBlock 调用dll
方法1: 直接使用方法需要用到lib和h文件
lib文件添加到codeblock的Project build option \ Linker Settings 中的Other linker setting中;

#ifdef __cplusplus
extern "C" {
#endif 

	__declspec(dllimport) int __cdecl myPuts(char * lpszMsg)
	
#ifdef __cplusplus
}
#endif

方法2: 使用LoadLibrary的方法,这样使用者不需要lib和h文件。
step1:定义函数(函数类型声明,函数指针)

typedef int(__cdecl* FuncMyProc)(char*); //声明接口函数1
step2:声明变量
WXHMODULE  hinstLib;  //HMODULE hinstLib;
bool fFreeResult, fRunTimeLinkSuccess = false;
FuncMyProc ProcAdd; //定义接口函数2

step3:初始化

    //接口函数初始化3
    ProcAdd=NULL;

   hinstLib = LoadLibrary(TEXT("D:\\Temp\\Dll1\\x64\\Debug\\Dll1.dll"));
	// If the handle is valid, try to get the function address.
	if (hinstLib != NULL)
	{
		ProcAdd = (FuncMyProc)GetProcAddress(hinstLib, ("myPuts")); //导入接口函数
	}

step4:调用接口函数

if (hinstLib != NULL)
{
	// If the function address is valid, call the function. //使用接口函数4
	if (NULL != ProcAdd)
	{
		fRunTimeLinkSuccess = TRUE;
		char msg[128];
		//sprintf(msg,"Message sent to the DLL function.);
		//strncpy()
		(ProcAdd)("Message sent to the DLL function.");//(ProcAdd)(msg);//(ProcAdd)(L"Message sent to the DLL function\n");
	}
}

step5:退出,关闭dll的使用

 if (hinstLib != NULL)//关闭接口函数5
	{
		// Free the DLL module.
		fFreeResult = FreeLibrary(hinstLib);

		ProcAdd=NULL;
	}

三. 注意事项
1. dll 和调用exe,x86\x63\win32, 需要保持一致,也就是必须是同样是32bit或64bit。
2. 建议dll使用UNICODE编码,这样可以避免汉字为乱码的情况。
3. 调用exe可以是多字节或unicode,dll也可以是多字节或unicode,两者可以不一样,建议保持一致。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值