2013-04-22 309 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