What is the best way to marshal a char array function argument?
- by Seh Hui 'Felix' Leong
Let say that given the following signature in LegacyLib.dll:
int Login(SysInst *inst, char username[8], char password[6]);
The simple way to marshal this function in C# would be:
[DllImport("LegacyLib.dll", CharSet=CharSet.Ansi)]
public static extern int Login(ref SysInst inst, string username, string password);
The problem of doing it in a such a naive way is that the managed string we passed into the username or password parameter could be longer than the array bounds and this could potentially cause a buffer overrun in LegacyLib.dll.
Is there a better way which overcomes this problem? i.e. is there any quick [MarshalAs(…)] magic that I could use to counter that?