I am having a problem acquiring the friendly name (dbcp_name) from DEV_BROADCAST_PORT using delphi.
I have tried using the microsoft help documentation which says it is a pointer to a null terminated string, but on that page there is a comment which indicates it is a variable-length structure, and dbcp_name is an array that contains the actual characters of the port name.
I have tried to extract this but I currently have not found a way as when I get it to return anything it is complete gibberish.
The code I have used follows:
PDevBroadcastPort = ^DEV_BROADCAST_PORT;
DEV_BROADCAST_PORT = packed record
dbcp_size : DWORD ;
dbcp_devicetype : DWORD;
dbcp_reserved : DWORD ;
dbcp_name : array[0..0] of ansichar; //TCHAR dbcp_name[1]; not valid
end;
I have tried different values for the length of the array, I had read somewhere that this was the correct declaration but I am not entirely sure. Also the commented out line is what the microsoft document gives for the line in C++
To extract the information I have tried this:
var
PData: PDevBroadcastPort;
FName: string;
...
PData := PDevBroadcastPort(Msg.lParam);
ShowMessage('Length '+Inttostr(length(PData^.dbcp_name)));
FName := '';
i:=0;
while((PData^.dbcp_name[i]) <> #0) and (i < 100) do
begin
FName := FName + (PData.dbcp_name[i]);
i := i +1;
ShowMessage(FName);
end;
I have tried setting the while loop to terminate at the length of the data structure but if I dont set it then it becomes huge.
Any help is appreciated and if I have left out any code which is needed for this question please let me know and I shall acquire it as soon as I can.
Thanks
The documentation doesn’t say it’s a pointer to a null-terminated string; it says it is a null-terminated string. That’s typical for arrays that are declared at the end of a record with a length of just one element.
There’s actually more memory after the designated record size, and that memory holds the remaining characters of the string. A pointer to that record field is also a pointer to the character data.
Your array-traversing code should work, too, assuming you have bounds checking disabled for that stretch of code (or else you’d get an exception when the program detected you reading beyond the first element of the array).
That all presupposes that
PDatareally is a pointer to aDev_Broadcast_Portstructure. You’ve given no information about what message you’re handing, so I don’t know whether you really have what you think you have.If you’re using Delphi 2009 or later, then the
TCHARtype in the C declaration is equivalent to Delphi’sWideChartype. Interpreting the field as an array ofAnsiCharwill get you wrong results, although for most port names, it might appear as though the array is a list of null-terminated one-character strings. Unless you’re sure you have non-Unicode data, you should just useCharandPChar, and let the Delphi version determine which data type you have.