简体   繁体   English

将C ++类编组为C#

[英]Marshal a C++ class to C#

I need to access code in a native C++ DLL in some C# code but am having issues figuring out the marshaling. 我需要在一些C#代码中访问本机C ++ DLL中的代码,但是在查找编组时遇到了问题。 I've done this before with code that was straight C, but seem to have found that it's not directly possible with C++ classes. 我之前使用直接C的代码完成了这项工作,但似乎发现使用C ++类并不是直接可行的。 Made even more complicated by the fact that many of the classes contain virtual or inline functions. 由于许多类包含虚函数或内联函数,因此更加复杂。 I even tried passing the headers through the PInvoke Interop Assistant , but it would choke on just about everything and not really no what to do... I'm guessing because it's not really supported. 我甚至尝试通过PInvoke Interop助手传递标题,但它会扼杀几乎所有东西而不是真的没有做什么...我猜是因为它不是真的支持。

So how, if at all possible, can you use a native C++ class DLL from .NET code. 那么,如果可能的话,你如何使用.NET代码中的本机C ++类DLL。 If I have to use some intermediary (CLR C++?) that's fine. 如果我必须使用一些中介(CLR C ++?),那很好。

There is really no easy way to do this in C# - I'd recommend making a simple wrapper layer in C++/CLI that exposes the C++ classes as .NET classes. 在C#中实际上没有简单的方法 - 我建议在C ++ / CLI中创建一个简单的包装层,将C ++类公开为.NET类。

It is possible to use P/Invoke and lots of cleverness to call C++ virtual methods , but I wouldn't go this route unless you really had no other choice. 可以使用P / Invoke和很多聪明来调用C ++虚拟方法 ,但除非你别无选择,否则我不会走这条路。

You might have a look at SWIG , if nothing else just to see how they handle the basic wrapper code (which SWIG generates). 您可以查看SWIG ,如果没有别的,只看他们如何处理基本包装代码(SWIG生成)。 I know next to nothing about C# native code bindings so I can't judge if their approach is sound, but they do a decent job with some of the other language bindings. 我对C#本机代码绑定几乎一无所知,所以我不能判断他们的方法是否合理,但是他们使用其他一些语言绑定做得不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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