ต่อเนื่องจาก C++ Dll Win32 Console Project
ในบทความนี้เป็นการใช้ C# เรียกใช้ DLL ที่เขียนจากภาษา C++
1. สร้างโปรเจ็กส์ C# เพื่อใช้งาน Dll ชื่อ CSConsole เป็นแบบ Console Application
เพิ่ม Code
using System;
using System.Collections.Generic;
using System.Linq; using System.Text; using System.IO; using System.Runtime.InteropServices; namespace CSConsole { class Program { [DllImport("../../../Debug/CDll.dll")] public static extern int Calc(int no1, int no2); [DllImport("../../../Debug/CDll.dll")] internal static extern int _flushall(); static void Main(string[] args) { int res; res = Calc(10, 20); Console.Write(res); } } }
เพิ่ม Code
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace CSWinForm { public partial class Form1 : Form { [DllImport("../../../Debug/CDll.dll")] public static extern int Calc(int no1, int no2); [DllImport("../../../Debug/CDll.dll")] internal static extern int _flushall(); public Form1() { InitializeComponent(); int res; res = Calc(10, 20); MessageBox.Show(res.ToString()); } }
ที่มา: Platform Invoke Tutorial