LoginSignup
13
22

More than 3 years have passed since last update.

[C++/C#]C#をC++/CLIでラップしてC++アプリから呼ぶ

Posted at

やりたいこと

すでにC#で作ってあるライブラリ(dll)を、C++のアプリから呼びたい。
方法として、C#のdllをC++/CLIでラップして、C++から呼ぶということを試してみる。

C#dllを作る

クラスライブラリ(.NET Framework)のプロジェクトを新規追加し、下記のコードを追加する。

DllCs.cs
namespace DllCs
{
    public class DllCsClass
    {
        public static int Add(int a, int b) => a + b;
    }
}

C++/CLIのラッパーを作る

VisualC++ > CLR > CLRクラスライブラリ を選択し、プロジェクトを作成し、下記のコードを追加する。

CsWrapperCppCLI.cpp
// C#をC++/CLIでラップするラッパー関数群
#include "stdafx.h"
#include "CsWrapperCppCLI.h"

// C#(.net)のクラスのnamespace
using namespace DllCs;

// C++/CLIラッパー関数
double __cdecl Add(int a, int b)
{
    // ここで、C#(.net)のメソッドを呼ぶ
    int ret = DllCsClass::Add(a, b);

    return ret;
}

CsWrapperCppCLI.h
#pragma once

// エクスポートとインポートの切り替え
#ifdef VC_DLL_EXPORTS
#undef VC_DLL_EXPORTS
#define VC_DLL_EXPORTS extern "C" __declspec(dllexport)
#else
#define VC_DLL_EXPORTS extern "C" __declspec(dllimport)
#endif

VC_DLL_EXPORTS double __cdecl Add(int a, int b);

※参照に、DllCsのプロジェクトを追加。
※このあたりの書き方は、通常のC++からC++のDLLを呼ぶ方法と同じ。
 →こちら参照

ラッパーを呼ぶC++アプリを作る

C++のコンソールアプリのプロジェクトを作成し、下記コードを追加する。

ConsoleApplication1.cpp
#include "pch.h"
#include <iostream>
#include <Windows.h>

using namespace std; 

typedef int(*Add)(int p1, int p2);

int main()
{
    auto dll = ::LoadLibrary(L"CsWrapperCppCLI.dll");
    auto add = reinterpret_cast<Add>(::GetProcAddress(dll, "Add"));
    wcout << add(10, 20) << endl;

    system("pause");
}

※ここも、通常のC++からC++のDLLを呼ぶ方法(動的)と同じ。
 →こちら参照

参考

C#のメソッドをC++から呼ぶ方法
https://qiita.com/tetsurom/items/a0ad9bd24dbe513afdc4

コード

13
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
22