VC++のDLLをC#で使うなど

VC++でDLLを作る

  • [新しいプロジェクト] > [Visual C++] > [Win32アプリケーション] でプロジェクトを作成。
  • ここでは名前を MyCppDll にしたとする。
  • [アプリケーションの種類] は [DLL] を選択。
  • MyCppDll.cpp を下記のように編集してビルド。
#include "stdafx.h"

extern "C" __declspec(dllexport) int __stdcall MyAdd(int a, int b)
{
    return a + b;
}

VC++でDLLを使う

  • 同ソリューションに [新しいプロジェクト] > [Visual C++] > [Win32コンソール アプリケーション] でプロジェクトを作成。
  • ここでは名前を MyCppApp にしたとする。
  • MyCppApp を [スタートアップ プロジェクトに設定]。
  • [追加] > [参照] > [新しい参照の追加] で MyCppDll を追加。
  • MyCppApp.cpp を下記のように編集してビルド。
  • Ctrl+F5 で実行して動作を確認。(下記コードはふつうに実行すると一瞬で終了するため)
#include "stdafx.h"

extern "C" __declspec(dllexport) int __stdcall MyAdd(int a, int b);

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 10, b = 20;
    int c = MyAdd(a, b);
    printf("%d + %d = %d\n", a, b, c);
    return 0;
}

C#でDLLを使う

  • 同ソリューションに [新しいプロジェクト] > [Visual C#] > [コンソール アプリケーション] でプロジェクトを作成。
  • ここでは名前を MyCsApp にしたとする。
  • MyCsApp を [スタートアップ プロジェクトに設定]。
  • Program.cs を下記のように編集してビルド。
  • DLLのパス指定に注意。同ディレクトリに配置すればファイル名だけで可。
  • Ctrl+F5 で実行して動作を確認。(下記コードはふつうに実行すると一瞬で終了するため)
using System;
using System.Runtime.InteropServices;

namespace MyCsApp
{
    class Program
    {
        [DllImport(@"..\..\..\Debug\MyCppDll.dll")]
        extern static int MyAdd(int a, int b);
        
        static void Main(string[] args)
        {
            int a = 10, b = 20;
            int c = MyAdd(a, b);
            Console.WriteLine(a + " + " + b + " = " + c);
        }
    }
}

VC++で.NETのDLLを作る

こんどは.NETクラスライブラリのDLLを作ってみる。

  • [新しいプロジェクト] > [Visual C++] > [CLR] > [クラス ライブラリ] でプロジェクトを作成。
  • ここでは名前を MyClrDll にしたとする。
  • MyClrDll.h と MyClrDll.cpp を下記のように編集してビルド。
#pragma once

using namespace System;

namespace MyClrDll {

    public ref class MyClrClass
    {
    public:
        static int MyAdd(int a, int b);
    };
}
#include "stdafx.h"
#include "MyClrDll.h"

using namespace MyClrDll;

int MyClrClass::MyAdd(int a, int b)
{
    return a + b;
}

C#で.NETのDLLを使う

  • 先に作成したC#アプリ MyCsApp を次のように変更する。
  • [追加] > [参照] で MyClrDll を追加。
  • Program.cs を下記のように編集してビルド。
  • Ctrl+F5 で実行して動作を確認。(下記コードはふつうに実行すると一瞬で終了するため)
using System;

namespace MyCsApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10, b = 20;
            int c = MyClrDll.MyClrClass.MyAdd(a, b);
            Console.WriteLine(a + " + " + b + " = " + c);
        }
    }
}