Menu

#1162 Invalid typemaps for raw wchar_t* strings

None
closed-fixed
csharp (37)
5
2022-03-18
2011-05-06
Anonymous
No

Swig generates invalid code for raw wchar_t * strings. While compiling this code VisualStudio C# compiler produces error:
Cannot implicitly convert type 'System.IntPtr' to 'string'

Example:
>> test.i
%include <wchar.i>
%immutable;
static const wchar_t *g_const;

>> testPINVOKE.cs
public static extern IntPtr g_const_get();

>> test.cs

public static string g_const {
get {
string ret = testPINVOKE.g_const_get(); // ERROR: Cannot implicitly convert type 'System.IntPtr' to 'string'
return ret;
}
}

> D:\dev\swigwin-2.0.3\swig.exe -csharp -c++ test.i

Currently I'm using the following typemaps to workaround this problem
%typemap(imtype, inattributes="[MarshalAs(UnmanagedType.LPWStr)]", out="string", outattributes="[return: MarshalAs(UnmanagedType.LPWStr)]" ) wchar_t * "string"
%typemap(out) wchar_t * %{ $result = (wchar_t *)SWIG_csharp_wstring_callback((const wchar_t *)$1); %}

Discussion

  • Clint Herron

    Clint Herron - 2012-10-24

    I'm having this same problem ( OS/X 10.7.5, SWIG Version 2.0.7, Mono JIT compiler version 2.10.9 ). Sadly, the posted workaround doesn't seem to work for me (strings are mangled, and appear to be just pointing to garbage memory)

     
  • Olly Betts

    Olly Betts - 2022-03-18
    • status: open --> closed-fixed
    • Group: -->
     
  • Olly Betts

    Olly Betts - 2022-03-18

    With SWIG git master the code in test.cs looks better:

    public class test {
      public static string g_const {
        get {
          string ret = global::System.Runtime.InteropServices.Marshal.PtrToStringUni(testPINVOKE.g_const_get());
          return ret;
        }
      }
    
    }
    

    SWIG 4.0.2 generates the bad code so this was only fixed recently, it seems by: https://github.com/swig/swig/pull/1868

     

Log in to post a comment.