Visual Basic和Visual C++互动(标准DLL)

原文见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

posted on 2005-03-23 17:18  Michael Zhao  阅读(3223)  评论(0编辑  收藏  举报