C++/CLI(VIsual C++のCLRプロジェクト)というのを用いることでC#から呼び出すことができます。
たとえば簡単な関数(名前空間あり)・クラスを呼び出すスタティックライブラリを作ります(Win32プロジェクト
コード:
// CppFunctions.h
#pragma once
int CppGlobalFunc(int i);
namespace CppTestNamespace
{
int CppScopedFunc(int i);
}
// CppFunctions.cpp
#include <iostream>
#include "CppFunctions.h"
int CppGlobalFunc(int i)
{
std::cout << "CppGlobalFunc" << std::endl;
return i;
}
namespace CppTestNamespace
{
int CppScopedFunc(int i)
{
std::cout << "CppScopedFunc" << std::endl;
return i;
}
}
この2つの関数をC#/VB.NET/F#から呼べるようにC++/CLIのラッパークラスを作成します。
このコードは
CppSharpというのを用いて実現します。
コード:
//CppFunctions.h (C++/CLI)
// ----------------------------------------------------------------------------
// <auto-generated>
// This is autogenerated code by CppSharp.
// Do not edit this file or all your changes will be lost after re-generation.
// </auto-generated>
// ----------------------------------------------------------------------------
#pragma once
#include "CppSharp.h"
#include <../../CppTest/CppFunctions.h>
namespace CppTest
{
}
namespace CppTest
{
public ref class CppFunctions
{
public:
static int CppGlobalFunc(int i);
};
namespace CppTestNamespace
{
public ref class CppFunctions
{
public:
static int CppScopedFunc(int i);
};
}
}
// CppFunctions.cpp(C++/CLI)
// ----------------------------------------------------------------------------
// <auto-generated>
// This is autogenerated code by CppSharp.
// Do not edit this file or all your changes will be lost after re-generation.
// </auto-generated>
// ----------------------------------------------------------------------------
#include "CppFunctions.h"
using namespace System;
using namespace System::Runtime::InteropServices;
int CppTest::CppFunctions::CppGlobalFunc(int i)
{
auto __ret = ::CppGlobalFunc(i);
return __ret;
}
int CppTest::CppTestNamespace::CppFunctions::CppScopedFunc(int i)
{
auto __ret = ::CppTestNamespace::CppScopedFunc(i);
return __ret;
}
上記のラッパークラスを呼び出す C#のコードです。
コード:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CppTest;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(CppFunctions.CppGlobalFunc(123));
Console.WriteLine(CppTest.CppTestNamespace.CppFunctions.CppScopedFunc(456));
}
}
}