0

I've been tasked with writing a new interface to a legacy C++ DLL I don't have the source code for, which - for reasons beyond me - accesses a global class in the legacy application directly.

From the application, it's something like:

extern Interface *App;

...

Interface App*;   //  A pointer to our interface class.

Then, from the legacy DLL:

if( App->GetStatus() ) return false;

The Interface class that App refers to is quite trivial to rewrite in C#, but how can I make it the equivalent of extern so that the legacy C++ DLL can access it?

Thanks!

  • 1
    You are not going to get very far with this as long as your write `Interface App*`, understanding pointers is pretty critical to get somewhere. Calling C# code from C++ requires getting the CLR loaded first. There are many ways to do that the wrong way, that starts by using the "easy" ways. Using the #import directive in C++ is a right way. Educate yourself, ask your supervisor for the resources you need. – Hans Passant Mar 30 '15 at 23:00
  • Bear in mind that the poster has said he doesn't have access to the C++ source code, so loading the CLR might be a problem... – nevada_scout Apr 01 '15 at 13:38

1 Answers1

0

You could try using Robert Giesecke's "UnmanagedExports" nuget package to achieve this functionality like so:

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int left, int right)
    {
       return left + right;
    } 
}

However:

a) I believe this only works for methods, not classes and

b) the reason there isn't a native way to export a DLL in C# is because that the calling application must have the .NET framework loaded in order to access that entry point. This also applies to the UnmanagedExports nuget package that I linked to above.

You can hack your way around this by getting your C++ app to load mono before calling the C# app, but it doesn't sound like this is possible in your case.

(Also, UnmanagedExports will only work if you explicitly set a build target in your project's properties - eg. x86)

nevada_scout
  • 971
  • 3
  • 16
  • 37
  • The .net framework is loaded as soon as one of your exported methods is called. Your c++ app can even be using a different version of the framework. – jbriggs Mar 30 '15 at 23:00
  • This only happens if your app is written in C++/CLI. If your C++ code is unmanaged it will not load the .net framework – nevada_scout Mar 30 '15 at 23:07
  • I compiled a native c++ program from the command line `cl /EHsc MyConsoleApp.cpp /Fe: MyConsoleApp.exe` In the cpp file I have `typedef void (__stdcall * OPENDEVICES)();` `OPENDEVICES OpenDevices;` `HINSTANCE hGetProcIDDLL = LoadLibrary("MyCSharpLib.dll");` `OpenDevices = OPENDEVICES(GetProcAddress(HMODULE(hGetProcIDDLL), "OpenDevices") );` This works. MyCSharplib.dll is created with .Net 4.0. I have a customer that uses Visual Studio 2005 and has no problem using this in there application. – jbriggs Mar 31 '15 at 18:18