2013-04-22 135 views
0

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

它是*永远不会*正确的调用AllocHGlobal并传递0.如果pinvoke声明是正确的,那么你不能使用这个函数,它会导致内存泄漏。好的可能性是它不正确,从声明中移除* out *,并用Marshal.AllocHGlobal(666)创建足够大的缓冲区。 – 2013-04-22 10:05:05

回答

1

我认为,更好的办法来分配内存以空指针是:

IntPtr OutPtr = new IntPtr(); 
IntPtr ErrorPtr = new IntPtr(); 

如果pcp_Out是Unicode字符串,然后尝试使用: CharSet = CharSet.Unicode

+0

谢谢了,pcp_Out是ANSI格式。我编辑了我的问题来反映这一点。 – San 2013-04-22 09:42:15

+0

如果你给我这个库,我可以尝试正确调用该函数。 – 2013-04-22 10:23:37