2017年2月26日 星期日

將C編譯成DLL,給C#使用(2)

(1). 選擇"檔案" > "新增" > "專案"。

(2). 選擇"Visual C#" > "Windows桌面" > "Windows Form 應用程式",並且修改專案的"名稱"後按"確定"。

(3). 點選"方案總管"下的"From1.cs"開啟設計標籤頁,使用"工具箱"在Form1設計增加控制項"textBox1""textBox1""textBox1"與"button1",最後使用"滑鼠左鍵"點兩下"button1"。

(4). 跳到Form1.cs程式設計的檔案中,輸入程式。
a. 先加入
       using System.Runtime.InteropServices; //加入協同工作

b.
        [DllImport("ConsoleApplication1.dll", EntryPoint = "add")] //加入dll名稱
        public static extern  int add(int x, int y); //加入函式名稱
c.
            int a, b;
            a = Int32.Parse(textBox1.Text); //文字轉數字
            b = Int32.Parse(textBox2.Text);

            textBox3.Text = add(a, b).ToString(); //數字轉文字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Runtime.InteropServices;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("ConsoleApplication1.dll", EntryPoint = "add")]
        public static extern  int add(int x, int y);
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            int a, b;
            a = Int32.Parse(textBox1.Text);
            b = Int32.Parse(textBox2.Text);
 
            textBox3.Text = add(a, b).ToString();
        }
 
    }
}


(5). 之後先將上一章節產生的"xxx.dll"檔複製到目前專案下的,"\bin\Debug"的路徑下。

(6). 按"開始"編譯程式。

(7). 最後顯示結果。