簡體   English   中英

在C#中,如何調用返回包含字符串指針的非托管結構的DLL函數?

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

我得到了一個DLL(“InfoLookup.dll”),它在內部分配結構並從查找函數返回指向它們的指針。 結構包含字符串指針:

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

   Info* LookupInfo( int id );
}

在C#中,如何聲明結構布局,聲明Interop調用,以及(假設返回非空值)使用字符串值? 換句話說,我如何將以下內容翻譯成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
}

嘗試以下布局。 使用PInvoke Interop Assistant自動生成代碼。 手動編碼的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));
    }

}

有關示例,請參閱此netapi32.NetShareAdd互操作聲明。 它包含一個SHARE_INFO_502結構,帶有一個public string shi502_netname成員。 Pinvoke.net提供了更多示例。

您還需要在C#中實現該結構,確保正確使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM