sashoalm
sashoalm

Reputation: 79665

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).

What is the recommended way of doing it?

Upvotes: 0

Views: 111

Answers (3)

melak47
melak47

Reputation: 4850

Another way (also outlined in the article linked by Matten I believe) is to write the wrapper dll in C++/CLI.

You write a regular C++ class with DLL exports:

#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:

#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.

Upvotes: 3

Matten
Matten

Reputation: 17603

Another way is to host a CLR in the unmanaged process, an example is outlined in the linked article with examples. This is the solution we prefer because we don't need no COM interop. Another example is given at this MSDN page.

Upvotes: 2

sashoalm
sashoalm

Reputation: 79665

One way of doing it is by creating C# COM server, and then calling it's functions from a C++ COM client, as outlined in MSDN's COM Interop tutorial.

Upvotes: 2

Related Questions