简体   繁体   中英

Can I export a C++ interface with C-Style methods to a C# dll

I'm trying to avoid COM. I'm designing a mixture C# and C++ controls on a C++ exe.

One method I came up with is PInvoking my C++ exe from C#, and sending windows messages to the C# windows. However the amount of methods I call on the controls base class is too long to justify windows messages.

So, if it's possible to export a whole C# interface to a C++ exe, that would be way easier.

I want to avoid COM because I may have to support windows 2000, and doing COM without relying on the manifest would be a deployment hassle on a software package that currently doesn't set much in the registry.

You could write a C wrapper for each of your C++ controls, and PInvoke from C#.

For example this C++ class:

class Example
{
  public:
  int MyMethod(int param);
}

and in a extern "C" block in your c++ exe:

void * CreateExample() { return new Example(); }
int Example_MyMethod(void * handle, int param) { reinterpret_cast<Example*>(handle)->MyMethod(param)); }

and in C#:

public class Example
{
 private IntPtr handle;

 public Example()
 {
   handle = _CreateExample();
 }

 public int MyMethod(int param)
 {
    return _MyMethod(param);
 }

 [DllImport("yourdll.exe")]
 private static extern IntPtr _CreateExample();

 [DllImport("yourdll.exe")]
 private static extern int _MyMethod(IntPtr handle, int param);
}

I use C++/CLI with VS 2010 to do this. You can expose a DLL C interface that can be consumed in the usual way, the implementation would just marshal data from that interface to your C# assembly.

Related question I think Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI

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.

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