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

I was provided with a DLL ("InfoLookup.dll") that internally selects structures and returns pointers to them from the search function. Structures contain pointers to strings:

extern "C"
{
   struct Info
   {
      int id;
      char* szName;
   };

   Info* LookupInfo( int id );
}

In C #, how can I declare a structure structure, declare an Interop call, and (assuming a non-zero value is returned) use a string value? In other words, how do I translate the following into C #:

#include "InfoLookup.h"
void foo()
{
   Info* info = LookupInfo( 0 );
   if( info != 0 && info->szName != 0 )
      DoSomethingWith( info->szName );
   // NOTE: no cleanup here, the DLL is caching the lookup table internally
}
+3
source share
4 answers

Try the following layout. Code is automatically generated using the PInvoke Interop Assistant . Manual Encoding 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));
    }

}
+5

. netapi32.NetShareAdd interop. SHARE_INFO_502, public string shi502_netname. Pinvoke.net.

+2

#, Marshal, .

, :

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);
}
-2
source

All Articles