2013-04-22 4 views
0

아래 코드에서 pcp_Out은 시스템 날짜를 ANSI 형식으로 반환합니다.Marshal.PtrToStringAnsi의 정크 문자

  • 시스템 날짜가 반환되지만 정크 문자가 앞에 있습니까?

  • AllocHGlobal 올바른 초기화 방법은 입니다. 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)과 같이 충분히 큰 버퍼를 만듭니다. –

답변

1

내가 생각 출력, 빈 포인터에 메모리를 할당하는 더 나은 방법은 다음과 같습니다 pcp_Out 유니 코드 문자열을 경우

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

, 다음 사용하려고 : CharSet = CharSet.Unicode

+0

감사합니다. pcp_Out은 ANSI 형식입니다. 나는 그것을 반영하기 위해 나의 질문을 편집했다. – San

+0

저에게이 라이브러리를 제공하면 함수를 올바르게 호출 할 수 있습니다. –

관련 문제