In C#, how do I invoke a DLL function that returns an unmanaged structure containing a string pointer?

后端 未结 4 1012
天命终不由人
天命终不由人 2020-12-18 11:27

I have been given a DLL (\"InfoLookup.dll\") that internally allocates structures and returns pointers to them from a lookup function. The structures contain string pointer

4条回答
  •  无人及你
    2020-12-18 11:57

    Try the following layout. Code automatically generated using the PInvoke Interop Assistant. Hand coded LookpInfoWrapper()

    [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct Info {
    
        /// int
        public int id;
    
        /// char*
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)]
        public string szName;
    }
    
    public partial class NativeMethods {
    
        /// Return Type: Info*
        ///id: int
        [System.Runtime.InteropServices.DllImportAttribute("InfoLookup.dll", EntryPoint="LookupInfo")]
    public static extern  System.IntPtr LookupInfo(int id) ;
    
        public static LoopInfoWrapper(int id) {
           IntPtr ptr = LookupInfo(id);
           return (Info)(Marshal.PtrToStructure(ptr, typeof(Info));
        }
    
    }
    

提交回复
热议问题