2010年(5)
分类: C/C++
2010-01-18 12:08:49
以下代码在Win32和Linux下都能编译生成动态链接库文件。
===========================================
//--------------------------------------------------------
// MyDll.h
//--------------------------------------------------------
#ifndef _MY_DLL_H_
#define _MY_DLL_H_
#undef DLL_SPEC
#if defined (WIN32)
#if defined (DLL_DEFINE)
#define DLL_SPEC _declspec(dllexport)
#else
#define DLL_SPEC _declspec(dllimport)
#endif
#else
#define DLL_SPEC
#endif
namespace MyDll{
// class in dll
class DLL_SPEC CDllClass{
public:
static CDllClass* NewInstance(int x, int y);
void Print();
protected:
CDllClass(int x,int y);
protected:
int m_cx;
int m_cy;
};
// function in dll
extern "C" DLL_SPEC int global_mul(int a, int b);
}
#endif // _MY_DLL_H_
//--------------------------------------------------------
// MyDll.cpp
//--------------------------------------------------------
#include
#if defined (WIN32)
#define DLL_DEFINE
#endif
#include "MyDll.h"
namespace MyDll{
// functions in class
CDllClass* CDllClass::NewInstance(int x,int y)
{
return new CDllClass(x,y);
}
void CDllClass::Print()
{
printf("x=%d,y=%d\n",m_cx,m_cy);
}
CDllClass::CDllClass(int x, int y)
:m_cx(x),m_cy(y)
{
}
// global functions
int global_mul(int a, int b)
{
return a * b;
}
}
对于上述动态库文件,可以使用以下的代码调用
===========================================
//--------------------------------------------------------
//test.cpp
//--------------------------------------------------------
#include
#include
#ifdef WIN32
#include
#endif // WIN32
#undef DLL_DEFINE
#include "../MyDll/MyDll.h"
// a simple way to import a dynamic lib
// can be used both in win32 and linux
#ifdef WIN32
#pragma comment(lib,"MyDll.lib")
#endif
void test_dll(int x, int y)
{
MyDll::CDllClass *pDll;
int z = 0;
pDll = MyDll::CDllClass::NewInstance(x,y);
pDll->Print();
z = MyDll::global_mul(x,y);
printf("x=%d,y=%d,z=%d,x*y=%d\n",x,y,z,x*y);
}
// an efficient way to import functions in dynamic lib
void test_dll_func(int x,int y)
{
int z = 0;
#ifdef WIN32
typedef int (*P_FUNC) (int,int);
P_FUNC fMul = 0;
HINSTANCE hDll = LoadLibrary("MyDll.dll");
if ( hDll == NULL){
printf("Error: can not load library\n");
return;
}
fMul = (P_FUNC)GetProcAddress(hDll,"global_mul");
if ( fMul == NULL){
printf("Error: can not get function\n");
return;
}
z = fMul(x,y);
#else
z = MyDll::global_mul(x,y);
#endif
printf("In test_dll_func: ");
printf("x=%d,y=%d,",x,y);
printf("mul=%d,x*y=%d\n",z,x*y);
#ifdef WIN32
FreeLibrary(hDll);
#endif
}
//--------------------------------------------------------
//main.cpp
//--------------------------------------------------------
#include
#include
#include
void test_dll(int x, int y);
void test_dll_func(int x,int y);
int main()
{
srand(time(0));
int x = rand() % 100 + 1;
int y = rand() % 100 + 1;
test_dll(x,y);
test_dll_func(x,y);
return 0;
}
上述代码都既能在Win32下编译,也能在Linux下编译。
|