PInvoke stopped working after upgrading to VS 2012

I have a C # project that uses a native dll through PInvoke. To date, I am developing a project with VS2010 for both previewing XP and Windows 8.

Since then I have upgraded to versions of Windows 8 and VS2012. The same project now crashes as soon as I hit my first PInvoke. Ad C:

const char * func(void); 

C # P / Invoke Declaration:

  [DllImport("libspotify.dll",CharSet = CharSet.Ansi)] internal static extern string sp_build_id(); 

The calling convention is stdcall. Now this layout always worked fine, and I realized that const char * would automatically be bound to a string. However, when working with VS2012 on Windows 8, this leads to crashes. If I change the C # declaration to return IntPtr, it works.

Was it just luck that the previous version worked, or was the code ok? Is there a reason this doesn't work anymore? If I need to change all my line declarations to IntPtrs and manually do Marshaling, I have a long and boring task ahead!

+4
source share
1 answer

The previous version worked as luck. Your code has always been broken. With the return value of the string p / invoke marshaller

  • copies the context to a new line,
  • then calls the CoTaskMemFree pointer, which returns the native code.

For some reason, you succeeded in previous versions of Windows. But this crashes your latest version of Windows.

It is very likely that this line will be statically distributed in the DLL. And so you should not try to free him.

It looks like there is a little work ahead of you.

+3
source

Source: https://habr.com/ru/post/1437797/