아래 코드에서 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"
AllocHGlobal을 호출하고 0을 전달하는 것은 결코 절대로 * 정확하지 않습니다. pinvoke 선언이 올 바르면이 함수를 사용할 수 없으므로 메모리 누수가 발생합니다. 올바른 것이 아님을 알기에 선언에서 * out *을 제거하고 Marshal.AllocHGlobal (666)과 같이 충분히 큰 버퍼를 만듭니다. –