原文見Nicholas Skapura得 Interfacing VB and C++
VC++ DLL
1)DLL中的函式宣告
void __declspec(dllexport) CALLBACK TestFunc()
{
cout << "Inside the DLL!";
}
2)定義DEF檔案
LIBRARY "testDLL_Library"
DESCRIPTION "An example DLL for interfacing with C++"
EXPORTS
TestFunc @1
VC++用戶端調用TestFunc的代碼
1)先聲明
typedef int (WINAPI*ifunc)(int t);
ifunc RetInt;
2)通過LoadLibrary和GetProcAddress獲得函數指標。
HINSTANCE hLib = LoadLibrary("testdll_library.dll");
if(hLib == NULL)
{
cout << "ERROR: Unable to load library!" << endl;
getch();
return;
}
RetInt = (ifunc)GetProcAddress((HMODULE)hLib,"RetInt");
3)調用DLL中的函數。
if(RetInt !=NULL)
RetInt();
else
。。。
4)釋放DLL
FreeLibrary((HMODULE)hLib);
VB用戶端調用TestFunc的代碼
1)聲明
Declare Function RetInt Lib "../testdll_library.dll" (ByVal t As Integer) As Integer
2)調用
call RetInt(1)
詳細內容見<a href="http://www.flipcode.com/articles/article_vbdlls.shtml">Interfacing Visual Basic And C++</a>
其他
1)如果VB需要傳遞數組參數。那麼VC DLL需要按照下面的方式完成
short __declspec(dllexport) CALLBACK ArrayExample(LPSAFEARRAY FAR *ArrayData)
{
short *temp;
temp = (short*)(*ArrayData)->pvData;
return(temp[0]);
}
2)參數包含字串
BSTR __declspec(dllexport) CALLBACK StringExample(BSTR stringVar)
{
LPSTR buffer;
buffer = (LPSTR)stringVar;
::MessageBox(NULL,buffer,"in C++",0);
buffer = _strrev(buffer);
return(SysAllocString(stringVar));
}
3)返回字串。需要通過調用SysAllocString事先分配空間給字串。
return(SysAllocString(tempArray[index]));
4)回呼函數
//VC++ DLL
// In C++
void __declspec(dllexport) CALLBACK CallbackExample(long Addr1)
{
typedef void (__stdcall *FNPTR)(BSTR stringVar);
FNPTR FunctionCall;
LPSTR buffer = "hello!";
FunctionCall = (FNPTR)Addr1;
BSTR temp;
temp = ChartoBSTR("hello");
FunctionCall(SysAllocString(temp));
}
VB用戶端
Declare Sub CallbackExample Lib "../testdll_library.dll" (ByVal Addr As Long)
Public Sub voidFunc(ByVal stringVar As String)
MsgBox stringVar
End Sub