读书人

C++ Builder 动态 DLL调用解决方案

发布时间: 2012-03-05 11:54:02 作者: rapoo

C++ Builder 动态 DLL调用 - C++ Builder / Windows SDK/API
原来一直用DELPHI,对C/C++不熟。有如下问题,我用DELPHI写了一个DLL要用CB调用,
DLL中函数 声明是 function CreatMessageConnection(IP: string; Port: integer; CallForm: THandle): Boolean;stdcall;

用CB生成HPP 函数声明是extern PACKAGE bool __stdcall CreatMessageConnection(AnsiString IP, int Port, unsigned CallForm);

我现在想用 Library动态载入DLL,并执行CreatMessageConnection,如下代码中我的函数说明应该如何添加,谢谢大家,最好能给我讲讲原因!谢谢


HINSTANCE xx;
xx = LoadLibrary(RoDllName.c_str());
RO_DLL_HINSTANCE = xx;
if (int(xx)!=0) {
try
{
CM = GetProcAddress(xx,"CreatMessageConnection");
}
catch(Exception &e)
{
}

} else
{

}

[解决办法]
首先,从兼容性的方面考虑,我是不建议DLL的输出函数中使用String作为参数类型的,尽量用标准数据类型。
其次,就目前这个情况来说,可以这样调用:

C/C++ code
typedef bool (__stdcall *CREATEMESSAGECONNECTION)(String IP, int Port, HANDLE CallForm);HINSTANCE h = ::LoadLibrary(RoDllName.c_str());if (h){    CREATEMESSAGECONNECTION CreateMessageConnection = (CREATEMESSAGECONNECTION)            ::GetProcAddress(h, "CreatMessageConnection");    if (CreateMessageConnection)    {        CreateMessageConnection("ip", 端口, 句柄);    }    else    {        // 获取函数地址失败    }        ::FreeLibrary(h);}else{    // 装载DLL失败}
[解决办法]
建议delphi中string改为pchar。
function CreatMessageConnection(IP: pchar; Port: integer; CallForm: THandle): Boolean;stdcall;


C/C++ code
 typedef bool     __stdcall CreatMessageConnection (char *IP,int Port,THandle CallForm);      CreatMessageConnection *pCreatMessageConnection=(CreatMessageConnection *)GetProcAddress(DLLHandle,"CreatMessageConnection");      if( pCreatMessageConnection!= NULL )      {         if( pCreatMessageConnection("ip",0,Handle) != 0 )         {            ShowMessage("OK");//         }         else         {            ShowMessage("error");         }       }       else       {          ShowMessage("pCreatMessageConnection load error");       }
[解决办法]
typedef bool __stdcall (*CreatMessageConnection)(AnsiString , int , void *);//函数指针声明
HMODULE dllModule=LoadLibrary(dllname);//加载
if(dllModule){//加载成功
CreatMessageConnection myfunc=(CreatMessageConnection )GetProcAddress(dllModule,"CreatMessageConnection");
if(myfunc)
{
myfunc(....);//函数调用
}
FreeLibrary(dllModule);
}

读书人网 >C++ Builder

热点推荐