C ++ methods for generating DLL and calling DLL

Source: Internet
Author: User

I am original based on multiple related blog posts on the Internet

1) generate DLL

Create two files: XXX. H, XXX. cpp

The content of XXX. H is as follows:

# Ifdef build_xxx_dll
# Define export _ declspec (dllexport)
# Else
# Define export _ declspec (dllimport)
# Endif

Extern "C "{
Export void example (void );
......
}

The content of XXX. cpp is as follows:

# Define build_xxx_dll
# Include "XXX. H"

Void example (void)
{
}
......

Then compile from the DOS Console (assuming mingw has been installed and environment variables are added)
G ++-shared-wl, -- kill-at, -- output-def, XXX. Def-o xxx. dll XXX. cpp

(Because C ++ implements function overloading by modifying the function name, we must use extern "C" with the -- kill-at compilation option to avoid modifying the function name, build_xxx_dll macro is used to select the function prototype declaration)

2) Static Call DLL

Add the following content to the new file yyy. cpp;
# Include "XXX. H"
# Pragma comment (Lib, "XXX. dll ")

The generated DLL does not require def files or CPP files.
If XXX. H is not included, add the function prototype declaration in the H file to yyy. cpp.

You must add a DLL during compilation, as shown in the following code:
G ++-L.-O yyy.exe yyy. cpp XXX. dll

3) dynamic call of DLL

First, you need to include windows. h
# Include <windows. h>

You also need a handle to save the loaded DLL file.
Hinstance hdll = loadlibrary ("XXX. dll ");

Declare the corresponding function pointer type of the required function
Typedef void (* pfunc) (void );

Returns the pointer to a function.
Pfunc pF = (pfunc *) getprocaddress (hdll, "example ");

Release the DLL file after use.
Freelibrary (hdll );

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.