[英]Using DLL's in CPP
I am a newbie to CPP. 我是CPP的新手。 I have a Visual studio project which creates a dll. 我有一个Visual Studio项目,它创建一个DLL。 I need to write a simple code which calls the functions in this dll. 我需要编写一个简单的代码来调用这个dll中的函数。
Till now most of the questions I browsed dealt with problems where the dll was called from an external app. 到目前为止,我浏览过的大多数问题都涉及从外部应用程序调用dll的问题。
I want a very simple tutorial that introduces this concept. 我想要一个非常简单的教程来介绍这个概念。 It loads a dll once and then calls its functions repeatedly from a simple code and NOT an app. 它加载一次dll,然后从一个简单的代码而不是一个app重复调用它的函数。
A simple example or a link to it will be very helpful. 一个简单的例子或它的链接将非常有帮助。
Thanks in advance 提前致谢
The basic concept is:: 基本概念是::
MSDN Sample Code // Assuming you have correctly built DLL with exported functions. MSDN示例代码 //假设您已使用导出的函数正确构建DLL。 // A simple program that uses LoadLibrary and // GetProcAddress to access myPuts from Myputs.dll. //一个使用LoadLibrary和// GetProcAddress从Myputs.dll访问myPuts的简单程序。
#include <windows.h>
#include <stdio.h>
typedef int (__cdecl *MYPROC)(LPWSTR);
int main( void )
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary(TEXT("MyPuts.dll"));
// If the handle is valid, try to get the function address.
if (hinstLib != NULL)
{
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts");
// If the function address is valid, call the function.
if (NULL != ProcAdd)
{
fRunTimeLinkSuccess = TRUE;
(ProcAdd) (L"Message sent to the DLL function\n");
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}
You should export a function in dll project. 您应该在dll项目中导出一个函数。
Ex: "ExportFunc"
And You can use LoadLibrary, GetProcAddress in other project to use funciton in dll. 并且您可以在其他项目中使用LoadLibrary,GetProcAddress在dll中使用funciton。 Ex: 例如:
#include <windows.h>
#include <stdio.h>
typedef int (__cdecl *MYPROC)(LPWSTR);
int main( void )
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary(TEXT("DllName.dll"));
// If the handle is valid, try to get the function address.
if (hinstLib != NULL)
{
ProcAdd = (MYPRO`enter code here`C) GetProcAddress(hinstLib, "ExportFunction");
// If the function address is valid, call the function.
if (NULL != ProcAdd)
{
fRunTimeLinkSuccess = TRUE;
(ProcAdd) (L"Message sent to the DLL function\n");
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.