, 나는 단지의 경우 어쨌든 게시거야 ...
자신의 라이브러리에 액세스 할 수있는 래퍼를 작성하는 과정을 표준 .Net 라이브러리 중 하나에 액세스하는 것과 동일합니다. 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