【问题标题】:Where do I implement my MFC DLL functions?我在哪里实现我的 MFC DLL 函数?
【发布时间】:2013-02-28 14:43:32
【问题描述】:

我整个早上都在搜索谷歌,但我找不到我要找的东西。我正在为 MFC 修改的 Visual Studio 中创建一个常规 DLL。也就是说在项目向导中,我选择了

Win32 Project -> DLL -> MFC

我做了不只是从向导的主列表中单击 MFC DLL,这是所有在线教程所描述的。

我的问题很简单。在 .cpp 文件中,我只需要知道我应该实现我的方法(在 .h 文件中声明)内部还是外部 _tmain 函数。 里面有一条评论说

//TODO: code your applications behavior here

但我不确定这是否是我的实现所在。

作为参考,这里是 .cpp 文件:

// testmfcdllblah.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "testmfcdllblah.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(NULL);

    if (hModule != NULL)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            _tprintf(_T("Fatal Error: MFC initialization failed\n"));
            nRetCode = 1;
        }
        else
        {
            // TODO: code your application's behavior here.
        }
    }
    else
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
        nRetCode = 1;
    }

    return nRetCode;
}

【问题讨论】:

  • DLL 不包含主函数...如果 MFC 不同的话会很好奇。
  • 我认为这里的 _tmain 函数仅用于允许与 MFC 兼容,这意味着在外部实现我的方法。但他们实际上并没有说在哪里实施它们,所以我不太确定......
  • 查看this 文章。
  • 感谢您的文章,但这是我查看的仅适用于 MFC 的 DLL 的文章之一,我的是经过修改以与 MFC 一起使用的常规 DLL。
  • Dll 可以有一个 main 函数,就像它们可以定义一个 PE32 入口点一样;)

标签: c++ windows class dll mfc


【解决方案1】:

由于您无法在其他函数中实现函数/方法,因此您的方法实现需要在 _tmain 函数之外进行。

您引用的注释块可以替换为您的库的初始化实现。

因此,如果您要声明像 SayHello 这样的函数,则可能如下所示:

testmfcdllblah.h:

// Declaration
void SayHello(void);

testmfcdllblah.cpp:

void _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    // .. all the other stuff ..

    // TODO: code your application's behavior here.
    SayHello();

    // .. the rest of the other stuff ..
}

void SayHello()
{
    AfxMessageBox("Hello!");
}

【讨论】:

    【解决方案2】:

    在 C++ 中,您不能定义局部函数。你永远不会在 _tmain 中实现任何功能。

    当您使用向导创建 DLL 时,您应该添加一个头文件来定义您与 DLL 的接口。并且你应该在你实现函数的地方添加一个 .CPP 源文件。

    你可以在你找到的地方调用函数

    // TODO: change error code to suit your needs
    

    顺便说一句:我不知道为什么动态链接库的向导会创建一个主函数。

    【讨论】:

    • 因为 DLL 也可以定义入口点 ;) 当它们被加载到进程中时,这对于初始化它们很有用。据我所知,MFC 使用它来初始化 COM(和其他几个资源)......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-05-28
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多