Search code examples
c#pointersunsafewchar-t

C# unsafe context / pointer type of LPWStr


suppose we have an unsafe context, because I want to have a pointer to a wchar_t parameter which is passed from a unmanaged C++ code. For example:

unsafe public(int* A, ???* B)
{
    _myInt = A;
    _myString = B;
}

Everything is fine with the int parameter, but what about the ???* type? I know that to marshal a wchar_t to a C# string type for this method, one can write [MarshalAs(UnmanagedType.LPWStr)] before the parameter B. But I need some kind of a native pointer type for B in order to link this pointer to _myString field. Is there something like wchar_t in C# or what else can I do to have the pointer B stored elsewhere in the class? Thanks, Jurgen


Solution

  • Unless you have a problem with c# copying the string behind the pointer during the construction of a string... you can pull it off like this:

    public static unsafe int Strlen(char* start)
    {
      var eos = start;
    
      while (*(eos++) != 0);
      return (int) ((eos - start) - 1);
    }
    
    unsafe public(int* A, char* B)
    {
        _myInt = A;
    
        _myString = new String(B, 0, Strlen(B));
    }
    

    The constructor used here is documented in MSDN