我来自 C#/Java 背景,所以我试图弄清楚如何创建一个行为类似于 C# dll 的 C++ dll。
我已经尝试过__declspec(dllexport)
and __declspec(dllimport)
,但我只设法让它在静态方法上工作。我相信这是由于我的理解有限。
如何在 C++ 中导出类(包括私有成员在内)并能够像使用 C# 一样在引用端实例化它们?一些指向在线资源/教程的指针也可以。
我开始使用 MFC dll 模板,老实说,我不知道其中 90% 的用途以及为什么要从 CWinApp 继承。我试图标记类,CCppPracticeLibraryApp
但它不再编译。
// CppPracticeLibrary.h : main header file for the CppPracticeLibrary DLL
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
#ifdef CCppPracticeLibraryApp_EXPORTS
#define CCppPracticeLibraryApp_API __declspec(dllexport)
#else
#define CCppPracticeLibraryApp_API __declspec(dllimport)
#endif
// CCppPracticeLibraryApp
// See CppPracticeLibrary.cpp for the implementation of this class
//
class CCppPracticeLibraryApp : public CWinApp
{
public:
CCppPracticeLibraryApp();
static CCppPracticeLibraryApp_API void SayHelloWorld();
// Overrides
public:
virtual BOOL InitInstance();
DECLARE_MESSAGE_MAP()
};
定义文件:
//CppPracticeLibrary.cpp : 定义 DLL 的初始化例程。
#include "stdafx.h"
#include "CppPracticeLibrary.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define CCppPracticeLibraryApp_EXPORTS
BEGIN_MESSAGE_MAP(CCppPracticeLibraryApp, CWinApp)
END_MESSAGE_MAP()
// CCppPracticeLibraryApp construction
CCppPracticeLibraryApp::CCppPracticeLibraryApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
void CCppPracticeLibraryApp::SayHelloWorld()
{
printf( "Hello world");
}
// The one and only CCppPracticeLibraryApp object
CCppPracticeLibraryApp theApp;
// CCppPracticeLibraryApp initialization
BOOL CCppPracticeLibraryApp::InitInstance()
{
CWinApp::InitInstance();
return TRUE;
}
客户端/引用方法
// TestConsoleApplication.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "TestConsoleApplication.h"
#include "CppPracticeLibrary.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.
/*CCppPracticeLibraryApp* testCallingLibrary = new CCppPracticeLibraryApp();
testCallingLibrary->SayHelloWorld();*/
CCppPracticeLibraryApp::SayHelloWorld();
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
我希望能够取消注释上述代码中的以下几行:
/*CCppPracticeLibraryApp* testCallingLibrary = new CCppPracticeLibraryApp();
testCallingLibrary->SayHelloWorld();*/