开发者

How do I use functions from a DLL?

How do I use functions 开发者_运维知识库from a DLL? I'm a total newbie and I don't really understand how to use functions from a DLL file. I'm trying to use MS Visual Studio 2008 (C++).

My understanding is that the DLL files will have corresponding header files and as long as I include the header files and call the functions normally in my code, it should work? Is that correct? Then I would just need to have the compiled exe file be able to find the DLL?

Please let me know if that is a remotely correct understanding!

Thanks!

Russel


To reuse a function declared in a DLL you have 2 choices:

The first one (and preferable) is to include the corresponding header file declaring the function you want to use, and then linking to the corresponding .lib. This second step appears to be linking statically to the function, but in reality ends up being a stub call that will load the DLL to memory when the first function included in the corresponding DLL is called. For example, to use the CreateWindowEx function you include the "WinUser.h" header and link to the "User32.lib" library.

The second option is to load the library manually. For this you would call the LoadLibrary function to get a handle to the DLL exporing the function you want, and then use GetProcAddress to get a pointer to the function. The returned pointer needs to be cast to the appropriate type, and then you then you can use it as any regular function pointer. This option is only recommended if you do not have access to the implementer's header and library, because there is a risk of using incorrect parameters or a mismatched calling convention in your function declaration.

PS - I'm simplifying a bit, but this is the core of how the process works.


A very simple Google search returned the answer for you.

http://www.google.com/search?hl=en&site=&q=How+do+I+use+functions+from+a+DLL+in+Visual+Studio&btnG=Search

First link, Read a few sections and came accross 'Calling DLL functions from Visual Basic Applications' http://msdn.microsoft.com/en-us/library/dt232c9t.aspx


You are on the right track but missing an important steps.

In order to use a DLL, you also need to link with it's import library. You do this by specifying the name of the import library under Linker / Input / Additional Dependencies.


There are many ways to link DLLs to your C++ applications!

  1. Include DLL header file and Lib File (contain linking information) to your project and call DLL function as normal function. The disadvantage is that application will load the DLL when it starts and if it's not found at %path% or base directory it will throw an exception.

  2. Using LoadLibrary API and GetProcAddress API method to load library. In this way, you need to pass DLL path in LoadLibrary, if load is successful, you can use a function pointer to access the function you need to call. Read in detail with example here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜