I'm trying to automate a process in an as400 emulator (IBM's Personal Communications iSeries) and in order to do so, I'm using some code (that I totally did not steal from
This is the region from the emulator I was supposed to get, just "Sy":
This sometimes works and sometimes it doesn't. I tried on different parts of the emulator and the issue is the same. Getting the cursor position and sending a string work fine, it is just when I'm trying to get a string from the emulator.
I don't even know where to look for answers as this code was originally posted in 2005.
CodePudding user response:
I found the problem. Inside the method ReadScreen
I make a StringBuilder
that expects 3000 characters. As I'm using out
in the parameter of the method, I'm dealing with one memory address instead of just two variables. As I allocated space for at least 3000 characters, when the string I read is small, sometimes it comes with garbage from that "unused" space. What I did was change the expected size of the StringBuilder
to the length of the string I'm trying to read minus 1 (if it was just the length I will still get one garbage character). Here's the code:
public static UInt32 ReadScreen(int position, int len, out string txt)
{
StringBuilder Data = new StringBuilder(len - 1); //This line was the problem.
UInt32 rc = (UInt32)position;
UInt32 f = HA_COPY_PS_TO_STR;
UInt32 l = (UInt32)len;
UInt32 r = EhllapiFunc.hllapi(out f, Data, out l, out rc);
txt = Data.ToString();
return r;
}
My explanation might be wrong, as I'm still learning C# and the code was originally from 2005, but this modification worked for me. Feel free to correct me if I misunderstood something or if I got something wrong.