在win32程序中如果需要控制台
可以调用API:
AllocConsole()
#include<windows.h>
#include<iostream>
int WINAPI WinMain(HINSTANCE hpreinstance, HINSTANCE hinstance,LPSTR str, int show)
{
AllocConsole();
freopen("conout$","w",stdout);
using Fun_Sub = int(*)(int, int);
Fun_Sub sub;
HINSTANCE mydll;
try{
mydll = LoadLibrary(TEXT("./../Debug/DLL.dll"));
if (NULL == mydll)
throw 0;
sub = (Fun_Sub)GetProcAddress(mydll,"Sub");
if (NULL == sub)
throw 1;
}
catch (int &e)
{
if (0 == e)
std::cout << "加载dll失败" << std::endl;
if (1 == e)
std::cout << "获取函数Sub失败" << std::endl;
FreeLibrary(mydll);
return -1;
}
std::cout << "call Sub" << sub(12, 5);
FreeLibrary(mydll);
FreeConsole();
return 0;
}
----------
ps:此篇由笔者临时需要却忘记conout$而记,上述代码可以不引用dll库,阅者自改,贴一下代码,保持程序完整性
----------
dll:
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"
#include<windows.h>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(NULL,L"dll was loading...",L"caption:",MB_OK);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
MessageBox(NULL, L"dll was unloading...", L"caption:", MB_OK);
break;
}
return TRUE;
}
__declspec(dllexport) int __stdcall add(int a, int b)
{
return a + b;
}
__declspec(dllexport) int __cdecl sub(int a, int b)
{
return a - b;
}
extern "C" __declspec(dllexport) int __stdcall Add(int a, int b)
{
return a + b;
}
extern "C" __declspec(dllexport) int __cdecl Sub(int a, int b)
{
return a - b;
}
freopen();
特殊文件名:”conout&”,”conin$”,”conerr”;