CryptFindLocalizedName returns an invalid string for multiple calls

When I execute CryptFindLocalizedName more than once from my .Net code, it returns with invalid information. The first call is accurate, but any calls to subsequences using the same string return bad data. I am not an expert on using Win32 api in C #, so I could do something wrong.

Here is my code ...

[DllImport("cryp32.dll", CharSet = CharSet.Auto]
public static extern string CryptFindLocalizedName(
  [In] string pwszCryptName
);

public static void Test()
{
    Console.WriteLine(CryptFindLocalizedName("My"));   // Returns "Personal"
    Console.WriteLine(CryptFindLocalizedName("My"));   // Returns "<weirdchar>ersonal"
}

I am trying to return friendly names to certificate stores.

What am I doing wrong?

+3
source share
1 answer

Probably the problem is that the marshaller does what it should not with the return value. The MSDN documentation states:

The returned pointer should not be freed.

# . .

[DllImport("cryp32.dll", CharSet = CharSet.Auto]
public static extern IntPtr CryptFindLocalizedName(
  string pwszCryptName
);

public static void Test()
{
    IntPtr retval = CryptFindLocalizedName("My");
    string name = Marshal.PtrToStringUni(retval);
}

, .

PtrToStringUni :

PtrToStringUni . , .

, CryptFindLocalizedName , .

+2

All Articles