C + + Build DLLs and method instances that invoke DLLs _c language

Source: Internet
Author: User

I am based on the network of multiple related blog posts original

1) Build DLL

Create two files xxx.h, xxx.cpp

Xxx.h contents are as follows:

#ifdef Build_xxx_dll
#define EXPORT __declspec (dllexport)
#else
#define EXPORT __declspec (dllimport)
#endif

extern "C" {
EXPORT void example (void);
... ...
}

Xxx.cpp contents are as follows:

#define Build_xxx_dll
#include "xxx.h"

void Example (void)
{
}
... ...

Then compile from the DOS console (assuming that MinGW is installed and adding environment variables)
g++-shared-wl,--kill-at,--output-def,xxx.def-o xxx.dll xxx.cpp

(because C + + uses the Modifier function name to implement the function overload, we should use extern "C" with the--kill-at compilation option to avoid modifying the function name, the Build_xxx_dll macro function is used to select Function Prototype declaration function)

2 Static Calling DLL

Add the following content to the new document Yyy.cpp;
#include "xxx.h"
#pragma comment (lib, "Xxx.dll")

The generated DLL does not require DEF files and CPP files to Also
Without xxx.h, it is necessary to add the function prototype declaration in H file into Yyy.cpp

You need to join the DLL at compile time, similar to this:
g++-L-o yyy.exe yyy.cpp xxx.dll

3 Dynamic Call DLL

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

You need a handle. Save the loaded DLL file
HInstance hdll=loadlibrary ("Xxx.dll");

Declare the corresponding function pointer type of the desired function
typedef void (*PFUNC) (void);

To get a function pointer to a function
Pfunc pf= (pfunc*) GetProcAddress (hDLL, "example");

When you are finished using, release the DLL file
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.