I’ve got a C# project that uses a native dll via PInvoke. To date, I’ve been developing the project with VS2010 on both XP and Windows 8 Consumer preview.
I’ve since updated to Windows 8 release, and VS2012. The same project now crashes as soon as I hit my first PInvoke. The C declaration is:
const char * func(void);
The C# P/Invoke declartion:
[DllImport("libspotify.dll",CharSet = CharSet.Ansi)]
internal static extern string sp_build_id();
Calling convention is stdcall. Now, this arrangement has always worked fine, and my understanding was that the const char* would automatically get marshaled to a string. However, when running from VS2012 on Windows 8, this crashes. If I change the C# declaration to return an IntPtr, it works.
Was it just luck that the previous version worked, or was the code ok? Is there any reason why this no longer works? If I need to change all my string declarations to IntPtrs, and do the Marshaling manually, then I’ve got a long and boring task ahead of me!
The previous version worked by luck. Your code has always been broken. With a string return value the p/invoke marshaller
CoTaskMemFreeon the pointer that the native code returned.For whatever reason, you got away with that on your previous versions of Windows. But it’s causing a failure on your latest version of Windows.
It’s exceedingly likely that this string will be statically allocated in the DLL. And so you should not be attempting to free it.
Looks like you have a bit of work ahead of you.