利用openssl管理证书及SSL编程第3部分:将MinGW编译的openssl dll导出def和lib供MSVC使用

将MinGW编译的openssl dll导出def和lib供MSVC使用

前面我们用mingw把openssl 编译成了动态库,得到下面2个dll文件:

libeay32.dll

ssleay32.dll

然后用下面的脚本生成Windows MSVC需要的模块定义文件(.def, .lib和.exp),

然后就可以在VC中使用了. 前提系统要安装VS.


系统要求:

Windows7+VS Studio (2008 and later)+MSYS

1) 根据32位dll生成模块定义文件的python代码:

#!/usr/bin/python
# filename: mklib32.py
#   -- Make 32bits windows module files from MinGW x86 .dll
# author: cheungmine@qq.com
# date: 2015-12-31
# note: run in MSYS
#######################################################################
import os, sys, platform

import optparse, ConfigParser

APPFILE = os.path.realpath(sys.argv[0])
APPNAME,_ = os.path.splitext(os.path.basename(APPFILE))
APPVER = "1.0"
APPHELP = "Make 32bits windows module files from MinGW .dll"

#######################################
# check if file exists
def file_exists(file):
    if file and os.path.isfile(file) and os.access(file, os.R_OK):
        return True
    else:
        return False


#######################################
# check system is msys or cmd
def check_system():
    # platform.uname():
    print " * platform:", platform.platform()
    print " * version:", platform.version()
    print " * architecture:", platform.architecture()
    print " * machine:", platform.machine()
    print " * network node:", platform.node()
    print " * processor:", platform.processor()
    if platform.architecture() != ('32bit', 'WindowsPE'):
        sys.exit("[ERROR] Platform not support.")


#######################################
# get MSVC path environment
def search_vspath():
    for msvc in [150, 140, 130, 120, 110, 100, 90, 80, 70, 60]:
        vsenv = "VS%dCOMNTOOLS" % msvc
        vspath = os.getenv(vsenv)
    
        if vspath:
            print " * %s='%s'" % (vsenv, vspath)
            return vspath
    sys.exit("[ERROR] VS_COMNTOOLS not found")


#######################################
# check dll file
def validate_args(dll_file, out_path):
    if out_path:
        if not os.path.exists(out_path):
            sys.exit("[ERROR] Specified out path not exists: %s" % out_path)
        if not os.path.isdir(out_path):
            sys.exit("[ERROR] Specified out path not dir: %s" % out_path)
    else:
        out_path = os.path.dirname(APPFILE)

    dllbases = []
    titles = []

    if file_exists(dll_file):
        dllpath = os.path.dirname(dll_file)
        dllbase = os.path.basename(dll_file)
        title, ext = os.path.splitext(dllbase)
        if ext.lower() != ".dll":
            sys.exit("[ERROR] Not a .dll file: %r" % dll_file)

        return (dllpath, [dllbase], [title], out_path)
    elif os.path.isdir(dll_file):
        for f in os.listdir(dll_file):
            pf = os.path.join(dll_file, f)
            if file_exists(pf):
                dllbase = os.path.basename(pf)
                title, ext = os.path.splitext(dllbase)
                if ext.lower() == ".dll":
                    dllbases.append(dllbase)
                    titles.append(title)
        if not len(dllbases):
            sys.exit("[ERROR] dll files not found in given path: %s" % dll_file)
        else:
            return (dll_file, dllbases, titles, out_path)
    else:
        sys.exit("[ERROR] Either file is missing or is not readable")


#######################################
def check_results(out_path, title):
    out_files = []

    def_file = os.path.join(out_path, title + ".def")
    if not file_exists(def_file):
        print "[ERROR] file not exists: %s" % def_file
    else:
        out_files.append(def_file)

    lib_file = os.path.join(out_path, title + ".lib")
    if not file_exists(lib_file):
        print "[ERROR] file not exists: %s" % lib_file
    else:
        out_files.append(lib_file)

    exp_file = os.path.join(out_path, title + ".exp")
    if not file_exists(exp_file):
        print "[ERROR] file not exists: %s" % exp_file
    else:
        out_files.append(exp_file)

    return out_files


###########################################################
# Usage for MSYS:
#   python mklib32.py -I "C:\DEVPACK\MinGW\msys\1.0\local\win32\bin" -O "./win32"
#
if __name__ == "__main__":
    print "*" * 54
    print "* %-50s *" % (APPNAME + " version: " + APPVER)
    print "* %-50s *" % APPHELP
    print "*" * 54

    if len(sys.argv) == 1:
        sys.exit("[ERROR] Input dll file not specified.")
    
    parser = optparse.OptionParser(usage='python %prog [options]', version="%prog " + APPVER)

    parser.add_option("-v", "--verbose",
        action="store_true", dest="verbose", default=True,
        help="be verbose (this is the default).")

    parser.add_option("-q", "--quiet",
        action="store_false", dest="verbose",
        help="quiet (no output).")

    group = optparse.OptionGroup(parser, APPNAME, APPHELP)

    parser.add_option_group(group)

    group.add_option("-I", "--dll-file",
        action="store", dest="dll_file", default=None,
        help="Specify input .dll file or path to export")

    group.add_option("-O", "--out-path",
        action="store", dest="out_path", default=None,
        help="Specify path for output files")

    (opts, args) = parser.parse_args()

    check_system()

    vspath = search_vspath()

    (dllpath, dllbases, titles, out_path) = validate_args(opts.dll_file, os.path.realpath(opts.out_path))

    print " * Input files:", dllpath
    for dll in dllbases:
        print " *             :", dll
    print " * Output path:", out_path

    out_dict = {}
    for i in range(0, len(dllbases)):
        print "-"*50
        dllbase = dllbases[i]
        title = titles[i]
        dll_file = os.path.join(dllpath, dllbase)

        print " * Make windows module definition: %s.def" % title
        msyscmd = 'pexports "%s" -o > "%s.def"' % (dll_file, os.path.join(out_path, title))
        ret = os.system(msyscmd)
        if ret != 0:
            sys.exit("[ERROR] MSYS command: %s" % msyscmd)

        print " * Make windows module import file: %s.lib" % title
        libcmd = 'cd "%s"&vsvars32.bat&cd "%s"&lib /def:%s.def /machine:i386 /out:%s.lib' % (vspath, out_path, title, title)
        ret = os.system(libcmd)
        if ret != 0:
            sys.exit("[ERROR] lib command: %s" % libcmd)
    
        out_dict[title] = check_results(out_path, title)

    print "=============== Output Files Report ==============="
    for title, files in out_dict.items():
        print "%s.dll =>" % title
        
        for f in files:
            print " * ", os.path.basename(f)

2) 根据64位dll生成模块定义文件的python代码:

#!/usr/bin/python
# filename: mklib64.py
#   -- Make 64bits windows module files from MinGW x64 .dll
# author: cheungmine@qq.com
# date: 2015-12-31
# note: run in MSYS
#######################################################################
import os, sys, platform

import optparse, ConfigParser

APPFILE = os.path.realpath(sys.argv[0])
APPNAME,_ = os.path.splitext(os.path.basename(APPFILE))
APPVER = "1.0"
APPHELP = "Make 64bits windows module files from MinGW .dll"

#######################################
# check if file exists
def file_exists(file):
    if file and os.path.isfile(file) and os.access(file, os.R_OK):
        return True
    else:
        return False


#######################################
# check system is msys or cmd
def check_system():
    # platform.uname():
    print " * platform:", platform.platform()
    print " * version:", platform.version()
    print " * architecture:", platform.architecture()
    print " * machine:", platform.machine()
    print " * network node:", platform.node()
    print " * processor:", platform.processor()
    if platform.architecture() != ('32bit', 'WindowsPE'):
        sys.exit("[ERROR] Platform not support.")


#######################################
# get MSVC path environment
# C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
def search_vspath():
    for msvc in [150, 140, 130, 120, 110, 100, 90, 80, 70, 60]:
        vsenv = "VS%dCOMNTOOLS" % msvc
        vspath = os.getenv(vsenv)

        if vspath:
            vcbat = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(vspath))), "VC\\vcvarsall.bat")
            if file_exists(vcbat):
                vspath = os.path.dirname(vcbat)
                print " * %s='%s'" % (vsenv, vspath)
                return vspath
    sys.exit("[ERROR] vcvarsall.bat not found")


#######################################
# check dll file
def validate_args(dll_file, out_path):
    if out_path:
        if not os.path.exists(out_path):
            sys.exit("[ERROR] Specified out path not exists: %s" % out_path)
        if not os.path.isdir(out_path):
            sys.exit("[ERROR] Specified out path not dir: %s" % out_path)
    else:
        out_path = os.path.dirname(APPFILE)

    dllbases = []
    titles = []

    if file_exists(dll_file):
        dllpath = os.path.dirname(dll_file)
        dllbase = os.path.basename(dll_file)
        title, ext = os.path.splitext(dllbase)
        if ext.lower() != ".dll":
            sys.exit("[ERROR] Not a .dll file: %r" % dll_file)

        return (dllpath, [dllbase], [title], out_path)
    elif os.path.isdir(dll_file):
        for f in os.listdir(dll_file):
            pf = os.path.join(dll_file, f)
            if file_exists(pf):
                dllbase = os.path.basename(pf)
                title, ext = os.path.splitext(dllbase)
                if ext.lower() == ".dll":
                    dllbases.append(dllbase)
                    titles.append(title)
        if not len(dllbases):
            sys.exit("[ERROR] dll files not found in given path: %s" % dll_file)
        else:
            return (dll_file, dllbases, titles, out_path)
    else:
        sys.exit("[ERROR] Either file is missing or is not readable")


#######################################
def check_results(out_path, title):
    out_files = []

    def_file = os.path.join(out_path, title + ".def")
    if not file_exists(def_file):
        print "[ERROR] file not exists: %s" % def_file
    else:
        out_files.append(def_file)

    lib_file = os.path.join(out_path, title + ".lib")
    if not file_exists(lib_file):
        print "[ERROR] file not exists: %s" % lib_file
    else:
        out_files.append(lib_file)

    exp_file = os.path.join(out_path, title + ".exp")
    if not file_exists(exp_file):
        print "[ERROR] file not exists: %s" % exp_file
    else:
        out_files.append(exp_file)

    return out_files


###########################################################
# Usage for MSYS:
#   python mklib64.py -I "C:\DEVPACK\MinGW\msys\1.0\local\win64\bin" -O "./win64"
#
if __name__ == "__main__":
    print "*" * 54
    print "* %-50s *" % (APPNAME + " version: " + APPVER)
    print "* %-50s *" % APPHELP
    print "*" * 54

    if len(sys.argv) == 1:
        sys.exit("[ERROR] Input dll file not specified.")
    
    parser = optparse.OptionParser(usage='python %prog [options]', version="%prog " + APPVER)

    parser.add_option("-v", "--verbose",
        action="store_true", dest="verbose", default=True,
        help="be verbose (this is the default).")

    parser.add_option("-q", "--quiet",
        action="store_false", dest="verbose",
        help="quiet (no output).")

    group = optparse.OptionGroup(parser, APPNAME, APPHELP)

    parser.add_option_group(group)

    group.add_option("-I", "--dll-file",
        action="store", dest="dll_file", default=None,
        help="Specify input .dll file or path to export")

    group.add_option("-O", "--out-path",
        action="store", dest="out_path", default=None,
        help="Specify path for output files")

    (opts, args) = parser.parse_args()

    check_system()

    vspath = search_vspath()

    (dllpath, dllbases, titles, out_path) = validate_args(opts.dll_file, os.path.realpath(opts.out_path))

    print " * Input files:", dllpath
    for dll in dllbases:
        print " *             :", dll
    print " * Output path:", out_path

    out_dict = {}
    for i in range(0, len(dllbases)):
        print "-"*50
        dllbase = dllbases[i]
        title = titles[i]
        dll_file = os.path.join(dllpath, dllbase)

        print " * Make windows module definition: %s.def" % title
        msyscmd = 'pexports "%s" -o > "%s.def"' % (dll_file, os.path.join(out_path, title))
        ret = os.system(msyscmd)
        if ret != 0:
            sys.exit("[ERROR] MSYS command: %s" % msyscmd)

        print " * Make windows module import file: %s.lib" % title
        libcmd = 'cd "%s"&vcvarsall.bat x86_amd64&cd "%s"&lib /def:%s.def /machine:amd64 /out:%s.lib' % (vspath, out_path, title, title)
        ret = os.system(libcmd)
        if ret != 0:
            sys.exit("[ERROR] lib command: %s" % libcmd)

        out_dict[title] = check_results(out_path, title)

    print "=============== Output Files Report ==============="
    for title, files in out_dict.items():
        print "%s.dll =>" % title
        
        for f in files:
            print " * ", os.path.basename(f)

使用起来非常简单, 打开MSYS命令行:


 $ python mklib64.py -I "C:\DEVPACK\MinGW\msys\1.0\local\win64\bin" -O "./win64"

******************************************************
* mklib64 version: 1.0                               *
* Make 64bits windows module files from MinGW .dll   *
******************************************************
 * platform: Windows-7-6.1.7601-SP1
 * version: 6.1.7601
 * architecture: ('32bit', 'WindowsPE')
 * machine: AMD64
 * network node: ThinkPad-W520
 * processor: Intel64 Family 6 Model 42 Stepping 7, GenuineIntel
 * VS120COMNTOOLS='C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC'
 * Input files: C:\DEVPACK\MinGW\msys\1.0\local\win64\bin
 *             : libeay32.dll
 *             : ssleay32.dll
 * Output path: c:\DEVPACK\Workspace\temp\win64
--------------------------------------------------
 * Make windows module definition: libeay32.def
 * Make windows module import file: libeay32.lib
Microsoft (R) Library Manager Version 12.00.21005.1
Copyright (C) Microsoft Corporation.  All rights reserved.

   正在创建库 libeay32.lib 和对象 libeay32.exp
--------------------------------------------------
 * Make windows module definition: ssleay32.def
 * Make windows module import file: ssleay32.lib
Microsoft (R) Library Manager Version 12.00.21005.1
Copyright (C) Microsoft Corporation.  All rights reserved.

   正在创建库 ssleay32.lib 和对象 ssleay32.exp
=============== Output Files Report ===============
ssleay32.dll =>
 *  ssleay32.def
 *  ssleay32.lib
 *  ssleay32.exp
libeay32.dll =>
 *  libeay32.def
 *  libeay32.lib
 *  libeay32.exp

64bits的文件名仍然是???32.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MSVC vs. MinGW 之 (lib,dll,def,obj,exe) vs (a,dll,def,o,exe) 玩转攻略手记 一份粗糙的研究记录,有待补完和整理。 MinGW: c -> o gcc -c a.c c -> exe gcc a.c libs.o -o a.exe (从主程序a.c,附加libs,生成a.exe) o -> exe gcc a.o b.o ... -o main.exe c -> dll,def,a gcc a.c -shared -o a.dll -Wl,--output-def,a.def,--out-implib,liba.a a -> dll a2dll liba.a dll -> a: dlltool --dllname a.dll --def a.def --output-lib liba.a (需要def文件) a -> def: dumpbin /exports lib.a > lib.def (在windows上调用,def需要修改) dll -> def : pexports a.dll -o > a.def (这里的-o是指给函数标序号) lib -> def : reimp -d a.lib lib -> a: (for __cdecl functions in most case) reimp a.lib; (for __stdcall functions) MSVC: c -> lib cl /LD a.c (注意已经定义了export列表) c -> dll cl /LD a.c c -> obj cl /c a.c c -> exe cl a.c /out:a.exe dll ->lib lib /machine:ix86 /def:a.def /out:a.lib (需要def文件) obj ->lib lib a.obj b.obj... /out:mylib.lib dll ->def DUMPBIN a.dll /EXPORTS /OUT:a.def (生成的def需要做修正) lib ->def reimp -d a.lib (这个要在MSYS+MinGW下用) 关于这些工具的适用范围可以很容易的理解和记忆。 dll和exe都是PE文件,所以可以使用pexports. lib和a是静态库文件,都是归档类型,不是PE格式。所以不能使用pexports. dll可以使用dlltool. lib可以使用lib, 和reimp(lib->a工具) 所有的bin文件,包括dll,exe,lib,a都可以使用dumpbin. 参考: http://hi.baidu.com/kaien_space/blog/item/5e77fafa2ba9ff16a8d3110a.html Mingw官网文档: http://www.mingw.org/wiki/MSVC_and_MinGW_DLLs http://oldwiki.mingw.org/index.php/CreateImportLibraries http://www.mingw.org/wiki/FAQ http://hi.baidu.com/opaquefog/blog/item/9b21b6deb324e25dccbf1ab7.html http://qzone.qq.com/blog/8330936-1238659272 http://hi.baidu.com/jzinfo/blog/item/b0aa1d308de99f9da8018e00.html 本篇测试用代码: 1. main.cpp #include #include #include "mylib.h" using namespace std; int main() { char str[]="Hello world!"; printhello(str); return 0; } 2. mylib.cpp #include #include #include "mylib.h" using namespace std; void EXPORT printhello(char *str) { cout << str << endl; } 3. mylib.h #define EXPORT __declspec(

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

车斗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值