5

I have an off the shelf product which supports custom plugins which need to be written in Unmanaged C. It doesn't support Managed Dll's and my language of preference is c#.

The information which needs to be passed back to the off the shelf product is very basic and can be held in a string.

So I was thinking I could do the following:

  1. Write the bulk of my code in a C# Dll.
  2. Write a wrapper in C++ Managed Code which calls my C# Methods.
  3. Write a basic Dll in unmanaged C which calls the Managed C++ Dll.

Now communicating between a Managed C++ and C# Dll is easy.

But I cant figure out how to call a managed c++ function from an unmanaged c dll. Any help with some simple sample code would be great.

Thanks

EDIT: I created a Code Project article on how I did this with Alex's answer below. http://www.codeproject.com/Tips/695387/Calling-Csharp-NET-methods-from-unmanaged-code

CathalMF
  • 9,705
  • 6
  • 70
  • 106

2 Answers2

6

You almost got it right. Just put numbers 2 and 3 in the same C++/CLI DLL. You can both use .NET classes and export C functions from a C++/CLI project.

extern "C" __declspec( dllexport ) void __stdcall PureExportC(
                                                    const wchar_t* param
)
{
    CSharpAssemblyNamespace::CSharpWorker worker;
    worker.DoWork( gcnew String(param) );
}
Alex
  • 7,728
  • 3
  • 35
  • 62
  • Hero. Brilliant stuff. – CathalMF Dec 10 '13 at 20:49
  • Just a quick one ontop of this. The C# Dll is now required to be in the current directory of the original application. Rather than in the current directory of the C++ Dll. Any idea how to change this? – CathalMF Dec 10 '13 at 20:56
  • @CathalMF you can probably link the C# and C++/CLI assemblies together, and get just one DLL. I haven't tried it, but [this answer](http://stackoverflow.com/questions/2609056/how-to-link-c-sharp-and-c-assemblies-into-a-single-executable) or [ILMerge](http://www.microsoft.com/en-us/download/details.aspx?id=17630) might work. – Alex Dec 11 '13 at 08:47
1

I don't think, you can do this. But you can write a c++ (unmanaged) plugin for the product. Then write a stand allone managed app with c#, start it from the plugin and communicate between them using named pipes or sockets.

dousin
  • 516
  • 1
  • 4
  • 10