が、私は念のためにとにかくそれを投稿します...
独自のライブラリにアクセスするためのラッパーを書き込む処理を標準の.Netライブラリの1つにアクセスするのと同じです。
CsharpProjectと呼ばれるプロジェクトでの例C#クラスコード:
using System;
namespace CsharpProject {
public class CsharpClass {
public string Name { get; set; }
public int Value { get; set; }
public string GetDisplayString() {
return string.Format("{0}: {1}", this.Name, this.Value);
}
}
}
あなたは、管理C++クラスライブラリプロジェクト(例はCsharpWrapperである)を作成し、それを基準として、あなたのC#プロジェクトを追加します。内部使用と参照プロジェクトで同じヘッダーファイルを使用するには、正しいdeclspecを使用する方法が必要です。これは、プリプロセッサディレクティブ(この場合はCSHARPWRAPPER_EXPORTS
)を定義し、#ifdef
を使用して、ヘッダーファイルのC/C++インターフェイスでエクスポートマクロを設定することによって実行できます。管理されていないインターフェイスヘッダーファイルには、管理されていないものが含まれている必要があります(または、プリプロセッサによって除外されている必要があります)。
アンマネージドC++インターフェイスヘッダーファイル(CppInterface。h):
#pragma once
#include <string>
// Sets the interface function's decoration as export or import
#ifdef CSHARPWRAPPER_EXPORTS
#define EXPORT_SPEC __declspec(dllexport)
#else
#define EXPORT_SPEC __declspec(dllimport)
#endif
// Unmanaged interface functions must use all unmanaged types
EXPORT_SPEC std::string GetDisplayString(const char * pName, int iValue);
次に、管理対象ライブラリファイルに含めることができる内部ヘッダーファイルを作成できます。これにより、using namespace
ステートメントが追加され、必要なヘルパー関数を含めることができます。
マネージドC++インタフェースヘッダファイル(CsharpInterface.h):
#pragma once
#include <string>
// .Net System Namespaces
using namespace System;
using namespace System::Runtime::InteropServices;
// C# Projects
using namespace CsharpProject;
//////////////////////////////////////////////////
// String Conversion Functions
inline
String^ToManagedString(const char * pString) {
return Marshal::PtrToStringAnsi(IntPtr((char *) pString));
}
inline
const std::string ToStdString(String^strString) {
IntPtr ptrString = IntPtr::Zero;
std::string strStdString;
try {
ptrString = Marshal::StringToHGlobalAnsi(strString);
strStdString = (char *) ptrString.ToPointer();
}
finally {
if (ptrString != IntPtr::Zero) {
Marshal::FreeHGlobal(ptrString);
}
}
return strStdString;
}
は、次に、あなただけのラッピングを行い、あなたのインターフェイスのコードを記述します。
マネージドC++インタフェースのソースファイル(CppInterface.cpp):
#include "CppInterface.h"
#include "CsharpInterface.h"
std::string GetDisplayString(const char * pName, int iValue) {
CsharpClass^oCsharpObject = gcnew CsharpClass();
oCsharpObject->Name = ToManagedString(pName);
oCsharpObject->Value = iValue;
return ToStdString(oCsharpObject->GetDisplayString());
}
は、それからちょうどあなたの管理されていないプロジェクトで管理されていないヘッダ、リンク時に生成されたの.libファイルを使用するようにリンカーに指示して、確認してくださいが含まれます.NetとラッパーのDLLは、アンマネージアプリケーションと同じフォルダにあります。
#include <stdlib.h>
// Include the wrapper header
#include "CppInterface.h"
void main() {
// Call the unmanaged wrapper function
std::string strDisplayString = GetDisplayString("Test", 123);
// Do something with it
printf("%s\n", strDisplayString.c_str());
}
アンマネージC/C++に公開したいインターフェイスはどれくらい複雑ですか? – CuppM
同様の質問/回答については、このリンクを参照してください:http://stackoverflow.com/questions/13293888/how-to-call-ac-sharp-library-from-native-c-using-c-cli-and-ijw 。 – amalgamate