[DllImport("func.dll"), CharSet = CharSet.Auto, SetLastError = true] public static extern IntPtr func( StringBuilder pwd ); StringBuilder pass = new StringBuilder( client.password ); IntPtr lpStrRet = Marshal.AllocHGlobal(128); lpStrRet = func( pass ); if (lpStrRet.ToInt32() == 0) throw new Exception("lpStrRet NULL"); string sRet = Marshal.PtrToStringAuto(lpStrRet); Marshal.FreeHGlobal(lpStrRet); // utilise sRet somme une string managée
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre question#define _CRT_SECURE_NO_WARNINGS #define WIN32_LEAN_AND_MEAN #include <windows.h> extern "C" __declspec( dllexport ) char* MYDllFunc(char* pCharData) { char* pRet = new char[64]; strcpy(pRet, "RETDLL_\0"); if( pCharData != NULL ) { strcat(pRet, pCharData); } return pRet; }
[DllImport("testDLL.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr MYDllFunc(IntPtr pwd); IntPtr lpStrRet = Marshal.AllocHGlobal(128); IntPtr pPass = Marshal.StringToHGlobalAnsi("un_mot_de_passe"); try { lpStrRet = MYDllFunc( pPass ); if (lpStrRet.ToInt32() == 0) throw new Exception("lpStrRet NULL"); string sRet = Marshal.PtrToStringAnsi(lpStrRet); Console.WriteLine("sRet = " + sRet + "\r\n"); } catch (Exception dllExc) { Console.WriteLine("ERR: " + dllExc.Message); } finally { /////////// Problème masqué par un try/catch try { Marshal.FreeHGlobal(lpStrRet); } catch { } }