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