如何 DllExport C++ 类以在 C# 应用程序中使用 [英] How do I DllExport a C++ Class for use in a C# Application

查看:21
本文介绍了如何 DllExport C++ 类以在 C# 应用程序中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含类myCppClass"的 C++ Dll 项目,并尝试使用以下代码将其导出,如下所述: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 ... };

我省略了public 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# 中的 DllImport-ing 上,并确保我在 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++ 类(它们实际上是名称错误的 C 接口).

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.

C 风格的界面看起来像这样(警告:未经测试的代码):

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 风格的包装器看起来像这样(警告:未经测试的代码):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆