简体   繁体   English

从C ++(MSVC编译器)调用C#dll

[英]Call a C# dll from C++ (MSVC compiler)

I have a C# dll, and I need to call some of its functions from my C++ program (native C++, not C++/CLI). 我有一个C#dll,我需要从我的C ++程序(本机C ++,而不是C ++ / CLI)中调用其某些功能。

What is the recommended way of doing it? 推荐的做法是什么?

Another way (also outlined in the article linked by Matten I believe) is to write the wrapper dll in C++/CLI. 另一种方法(我相信也可以在Matten链接的文章中进行概述)是用C ++ / CLI编写包装dll。

You write a regular C++ class with DLL exports: 您编写带有DLL导出的常规C ++类:

#pragma once

#ifdef CSCLIWRAPPER_EXPORTS
#define DLLAPI __declspec(dllexport)
#else 
#define DLLAPI __declspec(dllimport)
#endif

class DLLAPI CsCliWrapper
{
private:
    void *wrap;

public:
    CsCliWrapper();
    virtual ~CsCliWrapper();
};

reference the managed dll in the project, and use it in the implementation: 引用项目中的托管dll,并在实现中使用它:

#include "CsCliWrapper.h"
using namespace System;
using namespace System::Runtime::InteropServices;

CsCliWrapper::CsCliWrapper()
{
    CsPlugin^ obj = gcnew CsPlugin();

    wrap = GCHandle::ToIntPtr(GCHandle::Alloc(obj)).ToPointer();
}

CsCliWrapper::~CsCliWrapper()
{
    GCHandle h = GCHandle::FromIntPtr(IntPtr(wrap));
    h.Free();
}

Note however that this approach is not portable, at the moment there are no compilers supporting C++/CLI on linux or OSX. 但是请注意,这种方法不是可移植的,目前在Linux或OSX上没有支持C ++ / CLI的编译器。

一种实现方法是创建C#COM服务器,然后从C ++ COM客户端调用其功能,如MSDN的COM Interop教程所述

Another way is to host a CLR in the unmanaged process, an example is outlined in the linked article with examples . 另一种方法是在非托管流程中托管CLR, 链接的文章中附带了examples概述了一个示例 This is the solution we prefer because we don't need no COM interop. 这是我们首选的解决方案,因为我们不需要COM互操作。 Another example is given at this MSDN page . 此MSDN页面上给出了另一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM