Stdcall and DLL tools of MSVC and MinGW

Source: Internet
Author: User
Document directory
  • DEF file format
  • CL
  • LINK
  • LIB
  • Gcc
  • Ld
  • Dllwrap
  • Dlltool
  • Pexports
  • Microsoft Visual C ++
  • MinGW GCC
Stdcall and DLL tools of MSVC and MinGW

The_ StdcallCalling convention has been there for a very long
Time. While older calling conventions like_ PascalFell
Oblivion,_ StdcallBecame the standard calling convention of Win32
API functions. Unlike_ Cdecl(NativeCalling convention
Of C/C ++), it is supported in C/C ++, Visual Basic, Java, and other ages
Alike, which makes it the first choice when building a DLL for cross-language
Use.

The internal representations of both_ CdeclAnd_ Stdcall
Functions haveDecorations. In MSVC (Microsoft Visual C ++) and MinGW
(Minimalistic GNU for Windows) GCC,_ CdeclFunction will be prefixed
An underscore, and_ StdcallFunctions will have the beginning underscore
As well as be appended by the at-sign (@) Followed by the number
Of bytes in the argument list. So,
Double _ cdecl sin (double)
Will be decorated_ Sin, AndDouble _ stdcall sin (double)
Will be decorated_ Sin @ 8.

But things are not that simple. The decorations cocould change when they
Appear in DLLs or when they are produced by different compilers. The following
Table lists the names as are produced by MSVC, MinGW, Digital Mars C/C ++
Compiler (DMC), Borland C ++ Compiler/C ++ Builder (BCC ):

 

Calling Convention Internal * Msvc dll (w/DEF) Msvc dll (dllexport) DMC DLL MinGW DLL BCC DLL
_ Stdcall _Function@N Function _Function@N _Function@N Function@N Function
_ Cdecl _Function Function Function Function Function _Function

* For all but BCC, which has the same naming
Convention for symbols in code and exported name in DLL.

What a mess (especially when you notice that, for MSVC, whether
Name is exported by a DEF file or by
_ Declspec (dllexport) Attribute affects its
Naming decoration )! And although the ending decoration clearly shows how
Bytes the called function pops up from stack before returning, it is
Not necessarily the most frequently used form. E. g., the Win32 API
Functions in the system DLLs have no decoration at all, as in the case
Ones uses a DEF file when exporting functions with MSVC. Export DLLs
Intended for multi-language usage also follow this practice and use no
Decoration_ StdcallFunctions (although the Java Native
Interface, on Win32 platforms, will accept functions either undecorated
Or decorated in the Microsoft way, the latter being the preferred
Form). The remaining part of this article is thus specified Ted to
Creation and use of such DLLs with MSVC and MinGW, as well as
Introduction and comparison of related tools (there are good articles
Http://www.bcbdev.com/articles.htm
Explaining the complexities of DLLs with Borland C ++ Builder, so I need
Not bother to say anything more about it ).

Tools working with DEF files

First, I will talk about the DEF file format and the relevant tools used
With MSVC and MinGW. interval intricacies lie here.

DEF file format

We care about only two sections of the DEF file: the LIBRARY section and
The EXPORTS section. The LIBRARY section specifies the internal name
The DLL; and the EXPORTS section specifies the function or data items
Export. A short example follows:

LIBRARY    testdll.dll
EXPORTS
    cdeclFunction                       @1
    _stdcallFunction@8                  @2
    aliasName = cdeclFunction           @3

This DEF file defines three exports for a testdll. dll:
The first one is_ CdeclFunction, the second one_ Stdcall
Function, and the third one an alias of the first function (the left
Side of the "=" sign is an exported name and the right side the internal
Name). The three functions are also assignedOrdinals. A function
Can be called by its name or its ordinal.

CL

CLCan accept a DEF file on the command line, and it simply passes
The file nameLINK. E. g .,

cl /LD testdll.obj testdll.def

Will become

link /out:testdll.dll /dll /implib:testdll.lib /def:testdll.def testdll.obj
LINK

LINKIs our most important tool when treating DLL and DEF files
With MSVC. The command line mentioned inCLAlready shows the options
Commonly used when creating a DLL with a DEF file. The main point is: if
We do not use a DEF file when creating a DLL, the exported name of_ Stdcall
Function will be_Function@N; But if we use a DEF
File, the exported name cocould be eitherFunctionOr_Function@N;
If both names appear, only the undecorated form is used. However, we
Can force both forms of exports with the following lines in the EXPORTS
Section:

TestFunction = _TestFunction@4
_TestFunction@4 = _TestFunction@4
LIB

If we have the DLL from somebody else (no source available), and we have
The DEF file, the easiest way to create an import library is to use
LIB
Tool. The following syntax is often enough (check MSDN
For more details ):

lib /def:DEF_file

Nota bene: 1) it seemsLIBDoes not accept aliased forms
(It will simply ignore the part after the equal-sign); 2) it assumes all
Functions in the DEF file_ Cdecl. The second point lies in
Fact that the import library it produces will map each symbol in the DLL
To an internal name with an underscore prefixed, I. e., the linker using
The import library will try to resolve an undefined symbol_ Function
To the symbolFunctionIn the DLL. It takes no special care
The_ StdcallCalling convention. With some techniques we cocould
UseLIBTo produce import libraries_ StdcallFunctions,
But the caller cocould only call them by ordinal, not by name. The details
Are left as an exercise .

Gcc

Here we useGccTo callLd. The reason why we do not use
Ld
Directly is that usingGccIs generally more convenient. -Shared
Option is specially designed to produce DLLs. We cocould also use -Wl
Option to pass special link options.

Ld

GNULdHas configure options regarding DLLs, but we shall only focus
On four (help information follows ):

--add-stdcall-alias                Export symbols with and without @nn--kill-at     &nbbsp;                    Remove @nn from exported symbols--out-implib <file>   &nnbsp;            Generate import library--output-def <file>   &nnbsp;            Generate a .DEF file for the built DLL

EitherGccOrLdCan accept a DEF file directly on the command
Line. When a function (say,TestFunction @ 4) Is marked
_ Declspec (dllexport), And we have the following line in
EXPORTS section,

TestFunction = TestFunction@4

Both symbols will be exported to the DLL (LINKHas similar
Behaviour too). This behaviour is different fromDllwrap, Which
We shall talk of immediately.

Dllwrap

GNUDllwrapCocould produce a DLL by a DEF file. We generally use
Dllwrap
In the following syntax,

dllwrap --def DEF_file -o DLL_file OBJ_files [--output-lib LIB_file]

AndDllwrapWill transparently callGcc,Ld, AndDlltool
To fulfil its task. IfDllwrapIs asked to produce an import library
( -- Output-lib), It will letDlltoolDo it.
UnlikeLINKOrLd,DllwrapWill ignore
ExportSpecifications in an object file, and will not export
Name unless it is specifically listed as an exported name in the EXPORTS
Section (unless one does not use a DEF file at all ).

Dlltool

GNUDlltoolMay be used to create the files needed to build and
Use dynamic link libraries (DLLs). The following options are of interest
To us currently:

-l --output-lib <outname> Generate an interface library.-D --dllname <name>   &nnbsp;   Name of input dll to put into interface lib.-d --input-def <deffile>  Name of  .def file to be read in.-U --add-underscore   &nbspp;   Add underscores to symbols in interface library.-k --kill-at     ;         Kill @<n> from exported names.

DlltoolWorks likeLIB, And similarly it will
IgnoreThe part after the equal-sign in a DEF file, but it
Has its special features that somehow compensate for this sort coming:

  • The -U Option
    Makes the items in the DEF file map to symbols prefixed with
    Underscore in the DLL, and
  • The -K Option makes
    Items in the DEF file map to symbols stripped@NIn
    The DLL.
Pexports

This is a stand-alone open-source tool to produce a DEF file from a given
DLL. It is not distributed with MSVC or MinGW, and you may choose to download
Here
If you do not find it elsewhere.

The _ stdcall DLL and the import library

Having learned so much about the tools, now we are ready to do what we wanted.
We still needSed(Search on the Internet if you do not already
Have this useful tool), and a knowledge of regular expression is required
To understand thoroughly how it works.

Microsoft Visual C ++

The simplest way to produce a DLL is to use/LDCommand-line
OptionCL:

cl /LD OBJ_files

The resulting DLL will have exported names like_ MyFunction @ 8,
As is shown in the 'msvc DLL (dllexport) 'column
Above. To create symbols with no decoration, we must use a DEF file.
Following is an automatic way to create a DEF file from the DLL if
_ Declspec (dllexport)Is used to indicate which functions
Export:

link /out:DLL_file /dll OBJ_filespexports DLL_file | sed "s/^_\([[:alnum:]_]\+\)@[[:digit:]]\+/\1/" > DEF_file

At this step, you may also want to generate a DEF file to make the DLL
Usable with MinGW source.

pexports DLL_file | sed "s/^_\([[:alnum:]_]\+\)\(@[[:digit:]]\+\)/\1\2/" > DEF_for_gcc

Once you have the object files and the DEF file, creating the DLL and
Import library can be done in one step:

link /out:DLL_file /dll /def:DEF_file /implib:LIB_file OBJ_files

And you are free to use the DLL and the import library now as you wish.

MinGW GCC

If we do not need to control which functions to export caused t_ Declspec (dllexport),
We can type:

gcc -shared -o DLL_file OBJ_files -Wl,--output-def,DEF_filegcc -shared -o DLL_file OBJ_files -Wl,--kill-atdlltool -d DEF_file --dllname DLL_file --output-lib LIB_file --kill-at

If we want to use a DEF file to control which functions to export, we can
Start by (assuming_ Declspec (dllexport)Is used to indicate which
Functions to export)

gcc -shared -o DLL_file OBJ_files -Wl,--kill-at,--output-def,DEF_file

To produce a DEF file with exports like"Function=
Function@N
@Ordinal". After editing it to our will, the following commands
Will finish the job:

dllwrap --def DEF_file -o DLL_file OBJ_filessed "s/[[:alnum:]_]\+ *= *//" DEF_file > New_DEF_filedlltool -d New_DEF_file --dllname DLL_file --output-lib LIB_file --kill-at

And the import library is now at your hand to use.

 

I am not sure whether I have stated clearly, but I have listed all my
Findings when I struggled to find out how to use the DLL tools properly
And how to deal_ StdcallFunctions in DLLs. Hope you find
It useful.

ACKNOWLEDGEMENT:The MinGW mailing list provided much useful
Information; Luke Dunstan provided important suggestions and corrections.

2002-8-20, written by Wu Yongwei

2004-9-9, last updated by Wu Yongwei

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.