close

在C# 我還沒看過union 這種東西,

但C++總是有機會遇到,

那今天我用C#,要如何將 DLL中使用union 的資料讀出來呢?

對C++及union 有概念,它不就是幾個變數用相同記憶體位置,

只是長度不一定一樣

對C++而言,陣列就是用指標的概念,我想,C#也會是一樣的

 

首先我們先產生一個C++ 的DLL,就用我習慣的BCB寫

 

====Unit1.h====

typedef struct _MyUnion
{
    union
    {
        char    char_data;
        short   short_data;
        int     int_data;
    }u;
}MyUnion;

extern "C"
{
    void __stdcall SetData(MyUnion data);
    void __stdcall GetData(MyUnion *data);
}

 

====Unit1.cpp====

#include "Unit1.h"

MyUnion U1;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved)
{
    U1.u.int_data=0;
    return 1;
}
extern "C" __declspec(dllexport) void __stdcall SetData(MyUnion data)
{
    U1.u.int_data = data.u.int_data;
}
extern "C" __declspec(dllexport) void __stdcall GetData(MyUnion *data)
{
    data->u.int_data = U1.u.int_data;
}
 

====使用C#載入====

把DLL放到輸出路徑下

 

namespace TestDll
{
    public partial class Form1 : Form
    {

        [DllImport("Project1.dll")]
        private static extern void SetData(MyUnion data);

        [DllImport("Project1.dll")]
        private static extern void GetData(out MyUnion data);

        public Form1()
        {
            InitializeComponent();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            MyUnion U1 = new MyUnion();
            U1.u.int_data = 0x88888888;
            SetData(U1);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            MyUnion U1 = new MyUnion();
            GetData(out U1);
            textBox1.AppendText(U1.u.int_data.ToString("X8")+"\r\n");
        }
    }

    public class MyUnion
    {
        public U u=new U();        
        public class U
        {
            private byte[] char_buf=new byte[1];
            private ushort[] short_buf = new ushort[1];
            private uint[] int_buf = new uint[1];

            public byte char_data 
            {
                get { return char_buf[0]; }
                set { char_buf[0] = value; }
            }
            public ushort short_data 
            {
                get { return short_buf[0]; }
                set { short_buf[0] = value; }
            }
            public uint int_data 
            {
                get { return int_buf[0]; }
                set { int_buf[0] = value; }
            }
        }
    }
}
 

 

arrow
arrow
    文章標籤
    C++ C# DLL
    全站熱搜

    史克威爾凱特 發表在 痞客邦 留言(0) 人氣()