在下面的代码中,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