日期:2014-05-17  浏览次数:20999 次

C#对象转换成指针
如何将C#的某个对象转换成IntPtr或其他类型的指针?(Marshal.StructureToPtr除外的方法。前提的这样的,我开发一个C#组件给C++调用,C++那边需要获取组件中的某个对象的值,这个对象是由组件负责管理的,所以C++那边获得这个对象的指针即可。)

------解决方案--------------------
C#引用类型存的不就是内存堆中变量的地址吗,Mark
------解决方案--------------------
通过Marshal封送数据流,对方解析
------解决方案--------------------
只有值类型才可以得到指针。

引用类型不可以。道理很简单,引用类型指向托管堆,GC随时会回收的,GC不能跟踪是否有“指针”还在指向它。
------解决方案--------------------
类似如下,要指明布局

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
    public struct FSYDItems
    {
        [MarshalAs(UnmanagedType.I4)]
        private int _seltime;
        [MarshalAs(UnmanagedType.I2)]
        private UInt16 _itemtype;
        [MarshalAs(UnmanagedType.I4)]
        private int _amount;
        [MarshalAs(UnmanagedType.R4)]
        private float _price;
        [MarshalAs(UnmanagedType.R4)]
        private float _preprice;
        [MarshalAs(UnmanagedType.R4)]
        private float _afterprice;

        public int SelTime
        {
            get { return this._seltime; }
            set { this._seltime = value; }
        }
        public UInt16 ItemType
        {
            get { return this._itemtype; }
            set { this._itemtype = value; }
        }
        public int Amount
        {
            get { return this._amount; }
            set { this._amount = value; }
        }
        public float Price
        {
            get { return this._price; }