環境
- Windows 10 Home (64bit)
- Visual Studio Community 2019
手順
プロジェクトの作成
プロジェクト テンプレート:空のプロジェクト [C++]
プロジェクト名:dlltest
プロジェクトのプロパティ
全般
構成の種類:ダイナミック ライブラリ (.dll)
dlltest.cpp
extern "C" __declspec(dllexport)
int __stdcall square(int x)
{
return x * x;
}
初期化・終了化が必要なら DllMain
を用意する。
動作確認
VC++
プロジェクトの作成
プロジェクト テンプレート:空のプロジェクト [C++]
プロジェクト名:test1
test1.cpp
# pragma comment(lib, "dlltest")
# include <stdio.h>
extern "C"
int __stdcall square(int x);
int main()
{
int x = square(3);
printf("%d\n", x);
}
dlltest.dll
dlltest.lib
をプロジェクトのディレクトリにコピーする。
dll は実行時のカレントディレクトリなどパスの通った所に置く。
C#
プロジェクトの作成
プロジェクト テンプレート:Windows フォーム アプリケーション (.NET Framework) [C#]
プロジェクト名:WindowsFormsApp1
Form1.cs
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
//[DllImport("dlltest")]
[DllImport(@"C:\Projects\vc++\dlltest\Release\dlltest.dll")]
static extern int square(int x);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var x = square(9);
MessageBox.Show($"{x}");
}
}
}
DllImport
は相対または絶対パスで指定できる。