在下面的代碼中,pcp_Out應該以ANSI格式返回系統日期。Marshal.PtrToStringAnsi中的垃圾字符
系統日期被返回,但它前面有一些垃圾字符?
Is AllocHGlobal right right to initialize out IntPtr?
[DllImport("Open32env.dll", CharSet = CharSet.Ansi, ExactSpelling = false, EntryPoint = "CallOPLFunction", CallingConvention = CallingConvention.StdCall)] static extern int CallOPLFunction(long pl_Instr, IntPtr pcp_In, out IntPtr pcp_Out, out IntPtr pcp_ErrorMessage); static void Main(string[] args) { IntPtr OutPtr = Marshal.AllocHGlobal(0); IntPtr ErrorPtr = Marshal.AllocHGlobal(0); IntPtr inPtr = Marshal.StringToHGlobalAnsi(""); long invalue = 0; int ret = CallOPLFunction(invalue, inPtr, out OutPtr, out ErrorPtr); string Outstring = Marshal.PtrToStringAnsi(OutPtr,30); Marshal.FreeHGlobal(OutPtr); Marshal.FreeHGlobal(ErrorPtr); Marshal.FreeHGlobal(inPtr); }
輸出
Outstring = "h\0Qr\0\0\0\0Ä<g\a?\004/22/13 10:25"
它是*永遠不會*正確的調用AllocHGlobal並傳遞0.如果pinvoke聲明是正確的,那麼你不能使用這個函數,它會導致內存泄漏。好的可能性是它不正確,從聲明中移除* out *,並用Marshal.AllocHGlobal(666)創建足夠大的緩衝區。 – 2013-04-22 10:05:05