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

后端 未结 4 1013
天命终不由人
天命终不由人 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 12:17

    You need to implement the structure in C# as well, making sure to use the attributes in the Marshal class properly to ensure that the memory layout matches the unmanaged version.

    So, some variation of this:

    using System.Runtime.InteropServices;
    
    [DllImport("mydll.dll")]
    public static extern Info LookupInfo(int val);
    
    [StructLayout(LayoutKind.Sequential)]
    struct Info
    {
       int id;
       String szName;
    }
    
    private void SomeFunction
    {
       Info info = LookupInfo(0);
       //Note here that the returned struct cannot be null, so check the ID instead
       if (info.id != 0 && !String.IsNullOrEmpty(info.szName))
          DoSomethingWith(info.szName);
    }
    

提交回复
热议问题