雖然在DLL中定義指向主程序的函數(shù)指針,看似程序邏輯有些混亂,但工程實際應(yīng)用中有時卻得這么干,因此簡單總結(jié)一下,函數(shù)指針在開發(fā)中的應(yīng)用。
第一步: 創(chuàng)建一般的動態(tài)庫工程Win32s1
第二步: 在動態(tài)庫.h文件中,自定義函數(shù)指針類型,聲明導(dǎo)出函數(shù)
注:導(dǎo)出函數(shù)應(yīng)用到外部主程序的相關(guān)計算與結(jié)果
typedef float (*outFun)(int, int, int); //函數(shù)指針類型
// typedef + 類型標識 + (指針變量名稱) + (參數(shù)列表)
SBUI_API void getProfit(outFun fun); //聲明導(dǎo)出函數(shù)
注:導(dǎo)出函數(shù)的返回類型與函數(shù)指針應(yīng)用無關(guān)
第三步: 在動態(tài)庫的.cpp文件中,實現(xiàn)一個由外部函數(shù)執(zhí)行 + 動態(tài)庫函數(shù)執(zhí)行的一個動作
void getProfit(outFun fun)
{
int nGrossIncome = 90000; //總收入
int nLabourCosts = 1000; //人工成本
int nMaterialCosts = 2000; //材料成本
double nNetProfit = fun(
nGrossIncome,
nLabourCosts,
nMaterialCosts)/*求得稅前利潤*/
* (1 - 0.18);
char chNetProfit[512] = "\0";
sprintf(chNetProfit, "當期純利潤為 %f", nNetProfit); // #include
MessageBox(NULL, chNetProfit, "收益計算", MB_OK|MB_ICONINFORMATION);
}
第四步: 在主程序中實現(xiàn)成本計算函數(shù) setProfit,并調(diào)用DLL函數(shù)
float setProfit(int _nGrossIncome, int _nLabourCosts, int _nMaterialCosts)
{
int nSellingCosts = 5000;
return float(_nGrossIncome - nSellingCosts - _nLabourCosts - _nMaterialCosts);
}
#include "dll1.h"
#pragma comment(lib,"Win32s1.lib")
void CTestDlg::OnButton1()
{
getProfit(setProfit);
}
第一步: 創(chuàng)建一般的動態(tài)庫工程Win32s1
第二步: 在動態(tài)庫.h文件中,自定義函數(shù)指針類型,聲明導(dǎo)出函數(shù)
注:導(dǎo)出函數(shù)應(yīng)用到外部主程序的相關(guān)計算與結(jié)果
typedef float (*outFun)(int, int, int); //函數(shù)指針類型
// typedef + 類型標識 + (指針變量名稱) + (參數(shù)列表)
SBUI_API void getProfit(outFun fun); //聲明導(dǎo)出函數(shù)
注:導(dǎo)出函數(shù)的返回類型與函數(shù)指針應(yīng)用無關(guān)
第三步: 在動態(tài)庫的.cpp文件中,實現(xiàn)一個由外部函數(shù)執(zhí)行 + 動態(tài)庫函數(shù)執(zhí)行的一個動作
void getProfit(outFun fun)
{
int nGrossIncome = 90000; //總收入
int nLabourCosts = 1000; //人工成本
int nMaterialCosts = 2000; //材料成本
double nNetProfit = fun(
nGrossIncome,
nLabourCosts,
nMaterialCosts)/*求得稅前利潤*/
* (1 - 0.18);
char chNetProfit[512] = "\0";
sprintf(chNetProfit, "當期純利潤為 %f", nNetProfit); // #include
MessageBox(NULL, chNetProfit, "收益計算", MB_OK|MB_ICONINFORMATION);
}
第四步: 在主程序中實現(xiàn)成本計算函數(shù) setProfit,并調(diào)用DLL函數(shù)
float setProfit(int _nGrossIncome, int _nLabourCosts, int _nMaterialCosts)
{
int nSellingCosts = 5000;
return float(_nGrossIncome - nSellingCosts - _nLabourCosts - _nMaterialCosts);
}
#include "dll1.h"
#pragma comment(lib,"Win32s1.lib")
void CTestDlg::OnButton1()
{
getProfit(setProfit);
}

