DLL中导出ANSI和UNICODE函数

来源:互联网 发布:收费网站源码 编辑:程序博客网 时间:2024/05/24 05:13

模仿window中的DLL导出ANSI和UNICODE版本的函数,使用UNICODE宏来控制使用哪个版本;

在函数实际的执行代码UNICODE版本中,在ANSI函数的版本中只做参数的转换,及ANSI字符串转UNICODE字符串,然后调用UNICODE版本的函数。

 0、DLL头文件

 #ifdef ANSIUN_EXPORTS
#define ANSIUN_API __declspec(dllexport)
#else
#define ANSIUN_API __declspec(dllimport)
#endif

#ifdef _UNICODE
    #define  Show ShowW
#else    
    #define  Show ShowA
#endif

extern "C" __declspec(dllexport)  int __stdcall  ShowA(LPSTR lpStr);
 ANSIUN_API int ShowW(LPWSTR lpStr);
 1、DLL导出函数的实现

// ansiUN.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "ansiUN.h"
#include <iostream>




int  ShowW( LPWSTR lpStr )
{
    // std::wcout << lpStr << std::endl;
    MessageBoxW(NULL,TEXT(L"hello world."),TEXT(lpStr),0);
    wcscpy(lpStr, L"Title return FROM showw!");

    return 1;
}

extern "C" __declspec(dllexport)  int __stdcall ShowA(LPSTR lpStr)
{
    if (! lpStr)
        return 0;
    int nCntOfChs = MultiByteToWideChar(CP_ACP, 0, lpStr,-1, NULL, 0);
    LPWSTR lpwStr = new WCHAR[nCntOfChs]();
    if (! lpwStr) return 0;

    nCntOfChs = MultiByteToWideChar(CP_ACP, 0, lpStr, -1, lpwStr, nCntOfChs);
    ShowW(lpwStr);

    //从宽字符串转换窄字符串  
    //获取转换所需的目标缓存大小  
    DWORD dBufSize=WideCharToMultiByte(CP_OEMCP, 0, lpwStr, -1, NULL,0,NULL, FALSE);  

    //分配目标缓存  
    char *dBuf = new char[dBufSize];  
    memset(dBuf, 0, dBufSize);  
    //转换  
    int nRet=WideCharToMultiByte(CP_OEMCP, 0, lpwStr, -1, dBuf, dBufSize, NULL, FALSE);      
    strcpy(lpStr,dBuf);
    delete []dBuf;     
    delete[] lpwStr;
    lpwStr = NULL;
    return 1;
}

2、def文件

LIBRARY
;base64 decode encode

EXPORTS
; basic functions
ShowA
ShowW


原创粉丝点击