我如何DLLEXPORT一个C ++类在C#应用程序使用 [英] How do I DllExport a C++ Class for use in a C# Application
问题描述
我创建了包含一个类myCppClass一个C ++ DLL项目,并试图DLL使用以下code作为所描述导出:
<一href=\"http://msdn.microsoft.com/en-us/library/a90k134d(v=vs.80).aspx\">http://msdn.microsoft.com/en-us/library/a90k134d(v=vs.80).aspx
I have created a C++ Dll project which contains a class "myCppClass" and tried to Dll export it using the following code as described by: http://msdn.microsoft.com/en-us/library/a90k134d(v=vs.80).aspx
class __declspec(dllexport) CExampleExport : //public CObject
{ ... class definition ... };
我省略了公共CObject的为要求afx.h并暗示这是一个MFC DLL。我不知道这是好事还是不是,但它从DLL项目的默认设置是不同的。
I have omitted the "public CObject" as that requires afx.h and implies it is an MFC Dll. I am not sure if this is a good thing or not but it differed from the DLL project default settings.
从上面的链接文档导致我相信所有的公共职能和成员变量可用于进口。我如何在C#中做到这一点?可以简单的类实例?
From the above linked documentation I am led to believe that all "public functions and member variables" are available for import. How do I accomplish this in C#? Can simply instantiate the class?
编辑:我刚刚意识到文章的标题可能会产生误导。应该强调的是从C#-ING的DllImport,并确保我跟着文档中正确C ++
I just realized that the Title of the post may be misleading. The emphasis should be on DllImport-ing from C# and ensuring that I followed the documentation properly in C++
推荐答案
C#不能直接导入C ++类(这是有效的名称错位I2C接口)。
C# cannot directly import C++ classes (which are effectively name-mangled C interfaces).
您的选择是通过COM揭露类,创建一个使用C ++ / CLI或暴露C风格的接口的托管包装。我建议托管包装,因为这是最简单的,将给予最好的类型安全。
Your options are exposing the class via COM, creating a managed wrapper using C++/CLI or exposing a C-style interface. I would recommend the managed wrapper, since this is easiest and will give the best type safety.
A C风格的界面会是这个样子(警告:未经测试code):
A C-style interface would look something like this (warning: untested code):
extern "C" __declspec(dllexport)
void* CExampleExport_New(int param1, double param2)
{
return new CExampleExport(param1, param2);
}
extern "C" __declspec(dllexport)
int CExampleExport_ReadValue(void* this, int param)
{
return ((CExampleExport*)this)->ReadValue(param)
}
一个C ++ / CLI式的包装应该是这样的(警告:未经测试code):
A C++/CLI-style wrapper would look like this (warning: untested code):
ref class ExampleExport
{
private:
CExampleExport* impl;
public:
ExampleExport(int param1, double param2)
{
impl = new CExampleExport(param1, param2);
}
int ReadValue(int param)
{
return impl->ReadValue(param);
}
~ExampleExport()
{
delete impl;
}
};
这篇关于我如何DLLEXPORT一个C ++类在C#应用程序使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!