VC + + dynamic link library programming multiple threads

Source: Internet
Author: User
Tags export class function prototype sendmsg

Hello, read your written "VC + + DLL programming in simple and simple," especially the harvest. There's just one place I can't figure it out. When you export a global variable with a DLL, you specify the path to the. Lib (#pragma comment (lib, "DllTest.lib")), What about the path of the. dll file, I try to move the. dll file to another location, the program will not work properly, how to specify the. dll here.

I hope you can give me a solution in your busy schedule and appreciate it.

A programming enthusiast

Reply:

Windows searches for DLLs in the following order:

(1) The directory where the executable module of the current process resides;

(2) Current catalogue;

(3) Windows system directory, through the GetSystemDirectory function to obtain this directory path;

(4) Windows directory, through the GetWindowsDirectory function to obtain the path of this directory;

(5) The directory listed in the PATH environment variable.

Therefore, when implicitly linking, the path of the DLL file does not need to be specified or specified, and the system specifies that the DLL be searched according to the 1~5 steps, but the corresponding. lib file needs to specify the path; If you use Windows API functions LoadLibrary dynamically load DLLs, You can specify the path to the DLL.

Hello, I am a C + + beginner, I saw the teaching in Pconline, the benefit is not shallow. I was wondering if I could use multithreading in my DLL? The #using <mscorlib.dll> This instruction on MSDN implements multithreading, but does not seem to support DLLs.

Is there any way to support the production of multithreaded DLLs?? Can you give me a source code?

Reply:

Multiple threads can be handled in DLLs, and WIN32 support for multithreading is a capability provided by the operating system itself, not the type of program that the user writes. Even a console program, we can use multithreading:

#include <stdio.h>

#include <windows.h>

void Threadfun (void)

{

while (1)

{

printf ("This is new thread/n");

Sleep (1000);

}

}

int main ()

{

DWORD ThreadID;

CreateThread (NULL, 0, (lpthread_start_routine) threadfun, NULL, 0, &threadid);

while (1)

{

printf ("This is main thread/n");

Sleep (1000);

}

}

The result of the watcher's operation is to alternately output this is main thread, this is new thread, on the console window.

Let's look at the following example of a multithreaded DLL.

DLL program to provide an interface function Sendinit, in this interface to launch the sending thread Sendthreadfunc, in the corresponding work function of this thread we use the original socket socket text. Referring to Microsoft's classic book, "Windows core programming," we find it inappropriate to start a new thread when the DLL is loaded (that is, when the process is tied).

This thread waits for a CEvent event (for communication between threads), and the application calls the interface function sendmsg (INTERDATAPKT senddata) in the DLL to free this event. The following are the relevant source code:

(1) Send a paper to the thread entry function

///////////////////////////////////////////////////////////////////////////

Function Name: Sendthreadfunc

function function: Send paper to work thread entry function, use UDP protocol

////////////////////////////////////////////////////////////////////////////

DWORD WINAPI Sendthreadfunc (LPVOID lpvthreadparm)

Tip: You should use WINAPI declarations for thread functions, WINAPI are defined by macros as __stdcall

{

* * Create Socket/*

Sendsock = socket (af_inet, SOCK_DGRAM, 0);

if (Sendsock = = Invalid_socket)

{

AfxMessageBox ("Socket creation failed");

Closesocket (Recvsock);

}

/* Get target node port and address * *

struct sockaddr_in desaddr;

Desaddr.sin_family=af_inet;

Desaddr.sin_port=htons (Des_recv_port); Target node Receive port

DESADDR.SIN_ADDR.S_ADDR = inet_addr (DES_IP);

/* Send Data * *

while (1)

{

WaitForSingleObject (Hsendevent, 0xffffffffL);//Infinite wait event occurs

ResetEvent (hsendevent);

SendTo (Sendsock, (char *) sendsockdata.data, Sendsockdata.len, 0, (struct sockaddr*) &desaddr, sizeof (DESADDR));

}

return-1;

}

(2) InitInstance function of MFC Rule DLL

/////////////////////////////////////////////////////////////////////////////

Cmultithreaddllapp initialization

BOOL cmultithreaddllapp::initinstance ()

{

if (! AfxSocketInit ())//Initialize socket

{

AfxMessageBox (idp_sockets_init_failed);

return FALSE;

}

return TRUE;

}

(3) Start the Send thread

////////////////////////////////////////////////////////////////////////////////

Function Name: Sendinit

function function: DLLs are provided to the application calling interface for starting the send thread

/////////////////////////////////////////////////////////////////////////////

void Sendinit (void)

{

Hsendthread = CreateThread (NULL, 1000, Sendthreadfunc, this, 1, &usendthreadid);

}

(4) Sendmsg function

////////////////////////////////////////////////////////////////////////////////

Function Name: sendmsg

function functions: DLLs are provided to the application invocation interface for sending messages

/////////////////////////////////////////////////////////////////////////////

extern "C" void WINAPI sendmsg (interdatapkt senddata)

{

Sendsockdata = SendData;

SetEvent (hsendevent); Releasing a Send Event

}

The above procedure is just a simple example, in fact, in many engineering applications, we often see this approach. This DLL only makes a simple interface function sendmsg to the user, and it masks the technical details of multithreading with its application. Similarly, MFC provides the CSocket class at the bottom of its own multithreaded mechanism, so that we eliminate the use of multithreading.

Hello, look at your DLL article and find that the exported function can be declared directly with _declspec (dllexport) or defined in a. def file, as is the export of the variable. I want to know if the class can also be exported in a. def file. Your article only tells you how to add a _declspec (dllexport) export class before the class. Please advise.

Reply:

Generally we do not use the. def file to export classes, but this does not mean that classes cannot be exported with a. def file.

Using depends to view the DLLs generated by the "export class" routines of serial 2, we found that they had exported a number of "strange" symbol in Figure 21, which were processed by compilers. Therefore, in order to export a class with a. def file, we have to export all of these "strange" symbol, which is really not a good deal. So for classes, we'd better export directly to _declspec (dllexport).

Figure 1 The exported symbol when the class is exported

Hello, read your DLL article, know how to create a DLL, but in the face of a specific project, I still do not know what should be made into a DLL. Can you give me some experience in this field?

Reply:

DLL is generally used in software modules more fixed, more general-purpose modules can be reused, here is a very good example, is the hero Super Jie Ba. Liang Zhao new master of the processing of video and audio algorithm module has made two of DLLs, for the Super Jie Ba user Interface GUI program calls, it is a model of DLL design tutorial. The so-called "Same", Super Jie Ba interface again cool, the use of the several DLLs. Please refer to the book "Program Master Proverbs" in detail.

Hello, your DLL article is all about Windows, can you make a DLL on Linux OS? If you can, it's different from windows. Thank you.

Reply:

In the Linux operating system, dynamic Link technology can also be used for software design, but it is somewhat different from how the DLL is created and invoked under Windows.

The shared object technology in the Linux operating system (shared objects) corresponds to the DLLs in Windows, but the names are different, and their shared object files are suffix. So. Some of the functions associated with Linux shared object technology are as follows:

(1) Open Shared object, function prototype:

Opens the shared object named filename, and returns an action handle;

void *dlopen (const char *filename, int flag);

(2) Take function address, function prototype:

Get Interface Function Address

void *dlsym (void *handle, char *symbol);

(3) Turn off shared objects, function prototypes:

Closes the shared object for the specified handle

int dlclose (void *handle);

(4) Dynamic library error function, function prototype:

Error message returned when the shared object action function failed to execute

const char *dlerror (void);

From here we clearly see the shadow of Windows Api――loadlibrary, FreeLibrary and GetProcAddress. Another "Same".

This series of articles for the time being, you can continue to send the author email (mailto:21cnbao@21cn.com) Discussion DLL programming problems. For the mistakes and flaws in the article, you are also warmly welcome to correct me.

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.