[英]Can I export a C++ interface with C-Style methods to a C# dll
I'm trying to avoid COM. 我正在尝试避免使用COM。 I'm designing a mixture C# and C++ controls on a C++ exe.
我正在C ++ exe上设计混合的C#和C ++控件。
One method I came up with is PInvoking my C++ exe from C#, and sending windows messages to the C# windows. 我想出的一种方法是从C#调用C ++ exe,然后将Windows消息发送到C#Windows。 However the amount of methods I call on the controls base class is too long to justify windows messages.
但是,我在控件基类上调用的方法数量太长,无法证明Windows消息的合理性。
So, if it's possible to export a whole C# interface to a C++ exe, that would be way easier. 因此,如果可以将整个C#接口导出到C ++ exe,那将更加容易。
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. 我想避免使用COM,因为我可能必须支持Windows 2000,并且不依赖清单文件来进行COM部署会给当前在注册表中设置不多的软件包带来麻烦。
You could write a C wrapper for each of your C++ controls, and PInvoke from C#. 您可以为每个C ++控件编写一个C包装程序,并从C#中编写PInvoke。
For example this C++ class: 例如,此C ++类:
class Example
{
public:
int MyMethod(int param);
}
and in a extern "C" block in your c++ exe: 并在c ++ exe的extern“ C”块中:
void * CreateExample() { return new Example(); }
int Example_MyMethod(void * handle, int param) { reinterpret_cast<Example*>(handle)->MyMethod(param)); }
and in C#: 并在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. 我在VS 2010中使用C ++ / CLI来做到这一点。 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.
您可以公开一个可以以常规方式使用的DLL C接口,该实现只会将数据从该接口封送至您的C#程序集。
Related question I think Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI 相关问题,我想从C ++,反向P /调用,混合模式DLL和C ++ / CLI调用C#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.