[Mono-list] Problem using p/invoke on mono 1.0.1
Marcus
mathpup@mylinuxisp.com
Mon, 23 Aug 2004 02:50:59 -0500
I think that the problem has to do with some changes that were made to Mono
regarding its handling of strings as return types from P/Invoke method.
Behind the scenes, a char* is being returned, and the runtime converts the
char* into a System.String. In addition, MS.NET calls CoTaskFree() on the
char*. At one time Mono did not do this, but for compatibility with MS.NET,
its behavior changed. Apparently, libcrypt does not want user to free the
pointer that crypt() returns.
The work-around for this is to have your method return an IntPtr and then
convert the IntPtr to a string manually. For example, use the following in
the place of your WriteLine() statement:
string encrypted = Marshal.PtrToStringAnsi(UnixCrypt(arg,arg));
Console.WriteLine("UnixEncrypting {0} : {1}",arg,encrypted);
> I am trying to use libcrypt.so.2.3.2 with c#. This code has been working
> for quite a while but stopped to work now.
>
> here is a little sample program I wrote
>
> <snip>
> using System;
> using System.Text;
> using System.Security.Cryptography;
> using System.Web.Security;
> using System.Runtime.InteropServices;
>
>
>
> namespace CryptTest
> {
> class CryptTest
> {
> [DllImport ("crypt", EntryPoint="crypt", SetLastError=true)]
> private static extern string UnixCrypt(string text, string salt);
>
> [STAThread]
> static void Main(string[] args)
> {
> Console.WriteLine("have {0} args",args.Length);
> string arg = args[0];
> Console.WriteLine("UnixEncrypting {0} :
> {1}",arg,UnixCrypt(arg,arg));
> }
> }
> }
> </snip>
>
> When I try to run this with
>
> mono encrypt.exe rainer
>
> I get a NullReference Exception. I am a bit lost here since this code has
> been working beautifully for months. Either my debian upgraded its
> libcrypt version (which could easily be true) or upgrading to mono-1.0.1
> introduced the problem (which is less likely since I remember having the
> same issue on mono-1.0).