ネイティブ (unmanaged) な関数を、C++/CLI (managed) でラップして使う。
環境はVisual Studio 2005。
プロジェクトの参照設定や、インクルードディレクトリの設定など、適切に行うこと。
設定がわからない人は下部にあるリンクを参考にしてください。
ネイティブ (unmanaged) 関数
hello.hpp
#pragma once
#include <string>
void hello();
void show( int i );
void show( double d );
void show( std::string str );
hello.cpp
#include <iostream>
#include <typeinfo>
using namespace std;
#include "hello.hpp"
void hello() { cout << "Hello, world!" << endl; }
void show( int i ) { cout << "your input : " << i << endl;}
void show( double d ) { cout << "your input : " << d << endl; }
void show( string str ) { cout << "your input : " << str << endl; }
C++/CLI (managed) によるラッパクラス
hellolib.hpp
#pragma once
public ref class HelloLib {
public:
static void Show();
static void Show( System::Int32 i );
static void Show( System::Double d );
static void Show( System::String ^str );
};
hellolib.cpp
#include <cassert>
#include "hellolib.hpp"
#include "hello.hpp"
using namespace System;
using namespace System::Runtime::InteropServices;
void HelloLib::Show() { hello(); }
void HelloLib::Show( Int32 i ) { show( i ); }
void HelloLib::Show( Double d ) { show( d ); }
void HelloLib::Show( String ^str )
{
assert( str != nullptr );
IntPtr mptr = Marshal::StringToHGlobalAnsi( str );
show( static_cast<const char *>( mptr.ToPointer() ) );
Marshal::FreeHGlobal( mptr ); // メモリ解放
}
managedな言語 (C#) からの呼び出し
Program.cs
using System;
namespace hellouser
{
class Program
{
static void Main(string[] args)
{
HelloLib.Show();
HelloLib.Show(1);
HelloLib.Show(2.0);
HelloLib.Show("HelloLib.Show()");
}
}
}
参考リンク
アーカイブ
#archive_log
最終更新:2007年04月10日 14:22