簡體   English   中英

如何在 C# 中將非托管類型轉換為托管類型?

[英]How to convert unmanaged type to managed type in C#?

我正在嘗試在 C# 中為 LDAP 構建一個結構,但是如果我嘗試將 InPtr 轉換為我定義的結構,則會引發以下異常:嘗試讀取或寫入受保護的 ZCD69B4957F06CD818D7BF3D61 這通常表明其他 memory 已損壞。

        [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_sslinitW",
            SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern IntPtr ldap_sslinit(string hostName, uint portNumber, int secure);

        //https://docs.microsoft.com/en-us/windows/win32/api/winldap/ns-winldap-ldap
        [StructLayout(LayoutKind.Sequential)]
        public struct LDAP
        {
            [StructLayout(LayoutKind.Sequential)]
            struct ld_sb
            {
                System.UIntPtr sb_sd;
                byte Reserved1;
                System.UIntPtr sb_naddr;
                byte Reserved2;
            }
            string ld_host;
            UInt32 ld_version;
            byte ld_lberoptions;
            UInt32 ld_deref;
            UInt32 ld_timelimit;
            UInt32 ld_sizelimit;
            UInt32 ld_errno;
            string ld_matched;
            string ld_error;
            ulong ld_msgid;
            string Reserved3;
            UInt32 ld_cldaptries;
            UInt32 ld_cldaptimeout;
            UInt32 ld_refhoplimit;
            UInt32 ld_options;
        }

        private const uint LDAP_SSL_PORT = 636;

        static void Main(string[] args)
        {
            IntPtr ld = ldap_sslinit("test", LDAP_SSL_PORT, 1);
            var ldap = Marshal.PtrToStructure(ld, typeof(LDAP)); 
        }

在此之前,我嘗試使用private static extern LDAP ldap_sslinit(string hostName, uint portNumber, int secure); 但是,它返回以下錯誤:
“方法的類型簽名與 PInvoke 不兼容。”
我認為問題是由我定義的 LDAP 結構引起的,但我不知道從 unmanged 到 managed 的哪種類型是錯誤的。

非托管 管理
UINT_PTR UIntPtr
UCHAR* 字節[]
ULONG_PTR UIntPtr
PCHAR 細繩
烏龍 UInt32
UCHAR 字節

我是否在此表中使用了錯誤的映射?

  1. 您具體要完成什么。 C# 中有用於連接和使用 LDAP 的托管類型,不需要像您嘗試使用的本機實現。

  2. 如果由於某種原因您需要本機實現(注意:由於您被困在復雜握手的第一步,我建議使用托管實現),而不是嵌套ldap_sslinit結構的 c++ 定義在LDAP之外聲明它

struct ld_sb
{
    System.UIntPtr sb_sd;
    byte Reserved1;
    System.UIntPtr sb_naddr;
    byte Reserved2;
}


public struct LDAP
{
    ld_sb ld_sb;
    string ld_host;
    //...
}```

暫無
暫無

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

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