#1162 Invalid typemaps for raw wchar_t* strings

open
csharp (36)
5
2012-12-21
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


  • Anonymous
    2011-05-06

    Example

     
    Attachments
  • 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)