虽然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