【C#】【C++】C# から C++ のDLL を呼び出す (C# => C++)

■ サンプル

動作環境

 * 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


関連記事

C# から C++ のDLL を呼び出す際のトラブルシュート

https://blogs.yahoo.co.jp/dk521123/38070421.html

C++ / CLI ~ 入門編 ~

https://blogs.yahoo.co.jp/dk521123/38074280.html