【发布时间】:2016-09-13 13:55:45
【问题描述】:
您好,我在 Delphi 2007 应用程序中集成 DLL 时遇到了很多问题。
我怀疑我的调用参数有问题。 目前我有 2 个问题,但我认为它们是相互关联的。
1) 第一次调用 DLL: 来自 .h 文件:
extern "C" {
__declspec(dllexport) HRESULT Startup(char* version);
}
这个调用应该初始化 DLL 并返回 DLL 的版本。 HRESULT 应为 0,版本指针应包含版本。
我的 Delphi 代码:
function Startup(var version: Pchar): HRESULT; cdecl; stdcall; external 'myDLL.dll';
以及实际调用:
var
res : HRESULT;
Name1 : PChar;
test : AnsiString;
buf2: array [0..20] of AnsiChar;
begin
FillChar(buf2,20,0);
Name1:= @buf2[0];
res := RdmStartup(Name1);
//Here res = 0, but the Name1 stays empty, and the buf2 still contains 0.
end;
但结果为 0 调用成功。
然后我的第二个问题:我需要在 DLL 中调用一个函数来打开一个 COM 端口。
.h:
extern "C" {
__declspec(dllexport) HRESULT Open(HWND hWnd, int Port, DWORD BaudRate, DWORD Interval);
}
我的 Delphi 声明:
function Open(hWnd: HWND;Port : integer;BaudRate:LongInt;Interval:LongInt): HRESULT; cdecl; stdcall; external 'myDLL.dll';
我称之为:
res:= Open(self.Handle,5,115200,500);
在这里,我从 res 变量中的 DLL 中返回了失败。 我也有 DLL 的来源,我得到的失败来自 DLL 检查参数是否有效的部分,如果它们有效,它将继续,否则返回我当前得到的错误。
它正在检查的东西:
if(hWnd == NULL)
{
return false;
}
if(BaudRate != 2400 && BaudRate != 9600 && BaudRate != 38400 && BaudRate != 115200)
{
return false;
}
if(IntervalTimer < 300)
{
return false;
}
std::string strPortName = lexical_cast<std::string>( format("COM%d") % Port);
std::string strPortName(lpPortName.c_str());
std::string::size_type loci = strPortName.find("COM");
if( loci == std::string::npos )
{
return false;
}
return true;
上述其中之一在我的调用中返回 false,因为如果此函数的结果为 false,则 DLL 会给出我当前在结果中遇到的错误。 有谁知道我做错了什么?
我尝试了多种类型的组合,最后我坚持使用我在以下位置找到的转换:http://www.drbob42.com/delphi/headconv.htm 我也尝试过不同的方式来读取 char 指针,但都失败了.....
所以在这个阶段,我知道我成功地与 DLL 通信,因为我为 2 次调用返回了不同的 HRESULT,但我怀疑我的参数没有正常工作。
我使用的是 Delphi 2007,而 C++ DLL 是用 VS2010 构建的。
【问题讨论】:
-
你很幸运你把
stdcall放在cdecl之后,因为大多数返回HRESULT的函数都是stdcall,在这种情况下,它会否决cdecl。您可以删除cdecl,因为它只是一个与stdcall不兼容的不同调用约定。 -
@RudyVelthuis 我一直认为如果 DLL 是使用 embarcadero 以外的其他编译器构建的,那么您必须使用 cdecl 的参数不止一个。我想我当时错了
-
哦,太好了,我也尝试了所有的组合;)如果我没有定义它们中的任何一个,一切都会像现在一样工作。但我会删除 cdecl!
-
cdecl和stdcall,对冲你的赌注?
标签: c++ delphi dll parameters