【发布时间】:2019-04-24 23:19:45
【问题描述】:
我正在尝试将一段代码从 C 转换为 Delphi,其目标是填充一个结构,直到允许先前定义的最大限制。我尝试让 Delphi 版本更接近 C 代码(即使不是专业程序员)。
但我注意到,在我的 Delphi 代码中,似乎结构仅填充了 0 个值(FillMemory() 的结果),而不是填充了正确的值。
我该如何解决?下面我只显示相关代码。
C: (code of reference)
struct Client
{
SOCKET connections[2];
DWORD uhid;
HWND hWnd;
BYTE *pixels;
DWORD pixelsWidth, pixelsHeight;
DWORD screenWidth, screenHeight;
HDC hDcBmp;
HANDLE minEvent;
BOOL fullScreen;
RECT windowedRect;
};
static Client g_clients[256];
static Client *GetClient(void *data, BOOL uhid)
{
for(int i = 0; i < 256; ++i)
{
if(uhid)
{
if(g_clients[i].uhid == (DWORD) data)
return &g_clients[i];
}
else
{
if(g_clients[i].hWnd == (HWND) data)
return &g_clients[i];
}
}
return NULL;
}
BOOL recordClient()
{
Client *client = NULL;
BOOL found = FALSE;
DWORD uhid;
uhid = 27650; // Some value, only as example here
memset(g_clients, 0, sizeof(g_clients));
client = GetClient((void *) uhid, TRUE);
if(client)
return FALSE;
for(int i = 0; i < 256; ++i)
{
if(!g_clients[i].hWnd)
{
found = TRUE;
client = &g_clients[i];
}
}
if(!found)
{
wprintf(TEXT("User %S kicked max %d users\n"), "185.242.4.203", 256);
return FALSE;
}
return TRUE;
}
德尔福:
type
PClient = ^Client;
Client = record
Connections: array [0 .. 1] of TSocket;
uhId,
pixelsWidth,
pixelsHeight,
screenWidth,
screenHeight: Cardinal;
_hWnd: HWND;
Pixels: PByte;
hDcBmp: HDC;
minEvent: THandle;
fullScreen: Boolean;
windowRect: TRect;
end;
var
Clients: array [0 .. 255] of Client;
//...
function GetClient(Data: Pointer; uhId: Boolean): PClient;
var
I: Integer;
begin
Result := nil;
for I := 0 to 255 do
begin
if uhId then
begin
if Clients[I].uhId = Cardinal(Data) then
begin
Result := @Clients[I];
Break;
end;
end
else
begin
if Clients[I]._hWnd = HWND(Data) then
begin
Result := @Clients[I];
Break;
end;
end;
end;
end;
function recordClient: Boolean;
var
_client: PClient;
_uhId: Cardinal;
found: Boolean;
I: Integer;
begin
Result := True;
FillMemory(@Clients, SizeOf(Clients), 0);
_uhId := 27650; // Some value, only as example here
_client := GetClient(@_uhId, True);
if _client <> nil then
begin
Result := False;
Exit;
end;
found := False;
for I := 0 to 255 do
begin
if Clients[I]._hWnd = 0 then
begin
found := True;
_client := @Clients[I];
end;
end;
if not found then
begin
Writeln(Format('Client %s rejected, max allowed is %d clients.' + #13,
['185.242.4.203', 256])); // Only example values
Result := False;
Exit;
end;
end;
【问题讨论】:
-
这似乎是您的 GetClient 在您之前(已删除)的问题中返回 nil 的答案。
标签: delphi record delphi-10-seattle