Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

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

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 pointers:

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

   Info* LookupInfo( int id );
}

In C#, how can I declare the structure layout, declare the Interop call, and (assuming a non-null value is returned) utilize the 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...