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); %}
View and moderate all "bugs Discussion" comments posted by this user
Mark all as spam, and block user from posting to "Bugs"
Example
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)
With SWIG git master the code in test.cs looks better:
SWIG 4.0.2 generates the bad code so this was only fixed recently, it seems by: https://github.com/swig/swig/pull/1868