■ サンプル
動作環境
* Visual Studio 2017
C++側
* [Win32プロジェクト]で、「アプリケーションの種類」を[DLL]を選択する * プロジェクト名を「demodll」にし、DLL名を「demodll.dll」にするdemodll.h
#pragma once extern "C" { __declspec(dllexport) int sample01(int value1, int value2); __declspec(dllexport) void sample02(int* outResult); __declspec(dllexport) void sample03(char* outResult, int length); }demodll.cpp
// demodll.cpp : DLL アプリケーション用にエクスポートされる関数を定義します。 // #include "stdafx.h" #include "demodll.h" int sample01(int value1, int value2) { return value1 + value2; } void sample02(int* outResult) { *outResult = 4649; } void sample03(char* outResult, int length) { strcpy_s(outResult, length, "Hello World!"); }
C#側
* C++ 側をビルドして、「demodll.dll」を生成し、 「【プロジェクト名】\bin\Debug」or「【プロジェクト名】\bin\Release」内に置くSampleClass.cs
using System.Runtime.InteropServices; using System.Text; namespace WindowsFormsApp1 { class SampleClass { [DllImport("demodll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int sample01(int value1, int value2); [DllImport("demodll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void sample02(out int outResult); [DllImport("demodll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void sample03(StringBuilder outResult, int length); } }Form1.cs
using System; using System.Text; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { int result1 = SampleClass.sample01(2, 3); label1.Text = Convert.ToString(result1); int result2; SampleClass.sample02(out result2); label2.Text = Convert.ToString(result2); StringBuilder result3 = new StringBuilder(512); SampleClass.sample03(result3, 512); label3.Text = Convert.ToString(result3); } catch (Exception ex) { label1.Text = ex.Message; } } } }
■ 補足:デバッグについて
* プロジェクトのプロパティを選択し、 デバッグの項目の「アンマネージ コード デバッグを有効にする」に チェックを入れるhttps://toburau.hatenablog.jp/entry/20090216/1234756361
参考文献
http://www.84kure.com/blog/2014/07/16/73/http://qiita.com/ask/items/ee2ff5b8706effc0c3d8
http://qiita.com/TackKaiware/items/27ebcf10bb2624db197a