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?
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.
一种实现方法是创建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 . This is the solution we prefer because we don't need no COM interop. Another example is given at this MSDN page .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.