Marshal.PtrToStringAnsi中的垃圾字符

时间:2013-04-22 07:45:59

标签: c# .net marshalling dllimport

在下面的代码中,pcp_Out应该以ANSI格式返回系统日期。

  • 返回系统日期,但前面有一些垃圾字符?

  • AllocHGlobal是否正确初始化 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"

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题