What is the best way to marshal a char array function argument?

Posted by Seh Hui 'Felix' Leong on Stack Overflow See other posts from Stack Overflow or by Seh Hui 'Felix' Leong
Published on 2010-04-02T04:35:25Z Indexed on 2010/04/02 4:43 UTC
Read the original article Hit count: 325

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about marshalling

Related posts about .NET