繁体   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