zoukankan      html  css  js  c++  java
  • c#中引用c++动态库

            [System.Runtime.InteropServices.DllImportAttribute("visual_pick.dll", SetLastError = true)]
            public static extern int start();
    
    
            [System.Runtime.InteropServices.DllImportAttribute("visual_pick.dll", SetLastError = true)]
            public static extern int stop();
    
    
            [System.Runtime.InteropServices.DllImportAttribute("visual_pick.dll", SetLastError = true)]
            public static extern IntPtr getInfo();
    
    
            [System.Runtime.InteropServices.DllImportAttribute("visual_pick.dll", SetLastError = true)]
            public static extern int getInfoSize();

    调用名字需要跟c++中函数名一致,结构体类型使用指针接收(IntPtr),对应调用代码和实体定义如下:

    public void GetObjectInfo()
            {
                    try
                    {
                        //获取结构体字节大小
                        var size = Marshal.SizeOf(typeof(pickObjectInfoType));
                        //获取个数
                        var pickSize = getInfoSize();
    
                        if (pickSize > 0)
                        {
                            //获取对应方法内存地址,调用方法获取对应方法得到数组内存地址
                            var infosIntptr = getInfo();
                            for (int inkIndex = 0; inkIndex < pickSize; inkIndex++)
                            {
                                //根据获取内存地址进行数据偏移计算,得到对应指针指向的内存地址
                                IntPtr ptr = (IntPtr)(infosIntptr.ToInt64() + (inkIndex * size));
                                //根据内存地址转换结构体获取数据
                                pickList.Add((pickObjectInfoType)Marshal.PtrToStructure(ptr, typeof(pickObjectInfoType)));
                                Marshal.FreeHGlobal(ptr);
                            }
    
                        }
                    }
                    catch (Exception ex)
                    {
                    throw new Exception(ex.Message);
                    }
            }
    [StructLayout(LayoutKind.Sequential)]
        public struct pickObjectInfoType
        {
            public float x; 
            public float y; 
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 40)]//对应c++类型字节数,c++需要用char* 数组定义此类型
            public string z; 
        }
  • 相关阅读:
    OC3(字符串,值类)
    OC2(初始化方法)
    OC1(类和对象)
    postgresql 时间戳格式为5分钟、15分钟
    centos添加ftp用户并禁止外切目录
    postgresql 判断日期是否合法
    tigerVNC的简单使用教程(CentOS的远程桌面连接)
    linux awk解析csv文件
    由windows向linux上传下载文件方法
    codeblocks linux编译告警乱码解决办法
  • 原文地址:https://www.cnblogs.com/myparadiseworld/p/14651610.html
Copyright © 2011-2022 走看看