Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9366

VC++でDLLを作ってVC++/C#から呼び出してみた

$
0
0

環境

  • 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.dlldlltest.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は相対または絶対パスで指定できる。


Viewing all articles
Browse latest Browse all 9366

Latest Images

Trending Articles