菜鸟送分-关于DLL的初级知识
小弟刚刚开始学写DLL,昨天按照MSDN写了一个很简单的DLL,但是调用的时候却说找不到断口(GetLastError()=127),不知道为什么,各位给我的小程序找找毛病吧,谢谢!
-----------------------------------------------------------------------
调用DLL的测试代码
-----------------------------------------------------------------------
// File: RUNTIME.C
// A simple program that uses LoadLibrary and
// GetProcAddress to access myPuts from MYPUTS.DLL.
#include <stdio.h>
#include <windows.h>
typedef VOID (*MYPROC)(LPTSTR);
VOID main(VOID)
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary("myputs");
// 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 (fRunTimeLinkSuccess = (ProcAdd != NULL))
{
(ProcAdd) ("Hello, World!\n");
}
else
{
printf("Error = %ld\n",GetLastError());
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("message via alternative method\n");
}
-----------------------------------------------------------------------
DLL头文件
-----------------------------------------------------------------------
myputs.h
-----------------------------------------------------------------------
#ifdef MYPUTS_EXPORTS
#define MYPUTS_API __declspec(dllexport)
#else
#define MYPUTS_API __declspec(dllimport)
#endif
MYPUTS_API void myPuts(LPTSTR lpszMsg);
-----------------------------------------------------------------------
stdafx.h
-----------------------------------------------------------------------
#if !defined(AFX_STDAFX_H__202DBB33_8EE9_4155_A30F_6CA38D34C9BF__INCLUDED_)
#define AFX_STDAFX_H__202DBB33_8EE9_4155_A30F_6CA38D34C9BF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <windows.h>
#endif // !defined(AFX_STDAFX_H__202DBB33_8EE9_4155_A30F_6CA38D34C9BF__INCLUDED_)
-----------------------------------------------------------------------
DLL 代码
-----------------------------------------------------------------------
stdafx.cpp
-----------------------------------------------------------------------
#include "stdafx.h"
-----------------------------------------------------------------------
MyPuts.cpp
-----------------------------------------------------------------------
#include "stdafx.h"
#include "MyPuts.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
MYPUTS_API void myPuts(LPTSTR lpszMsg)
{
DWORD cchWritten;
HANDLE hStdout;
// Get a handle to the standard output device.
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Write a null-terminated string to the standard output device.
while (*lpszMsg)
WriteFile(hStdout, lpszMsg++, 1, &cchWritten, NULL);
}