雖然LAIN打我寫一個例子,不管怎樣,我萬一它張貼...
寫的包裝來訪問你自己的庫的過程與訪問標準.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 2009-12-01 16:35:55
看到這個鏈接的相似問題/答案:http://stackoverflow.com/questions/13293888/how-to-call-ac-sharp-library-from-native-c-using-c-cli-and-ijw 。 – amalgamate 2014-07-08 13:46:03