简体   繁体   English

使用C#在运行时确定的C ++ DLL

[英]Using C++ DLLs determined during runtime in C#

I'm working on a C# project at the moment and I have zero experience with C#. 我目前正在从事C#项目,对C#的经验为零。

We have a set of DLLs written in C++, they have the same classes and same functionality, but they work differently. 我们有一组用C ++编写的DLL,它们具有相同的类和相同的功能,但是它们的工作方式不同。 As an instance let's say our program converts BMP files. 举例来说,假设我们的程序转换了BMP文件。 We have DLLs for converting BMP to JPG, BMP to PNG and so forth. 我们有用于将BMP转换为JPG,将BMP转换为PNG等的DLL。

Our program which is written in C# somehow should wrap those DLLs, but not in a static way. 用C#编写的程序应该以某种方式包装这些DLL,但不能以静态方式包装。 We'd like to be able to change the DLL in use during runtime, and add new DLLs when need be (also during runtime). 我们希望能够在运行时更改正在使用的DLL,并在需要时(也在运行时)添加新的DLL。 Like plugins, if you will. 像插件一样,如果可以的话。

What would your suggestion be to implement this approach? 您对实施此方法有何建议?

If you don't know what all of your DLLs are ahead of time, you will probably need to call the Win32 function "LoadLibrary" "GetProcAddress" and "FreeLibrary." 如果您不知道所有DLL都提前了,则可能需要调用Win32函数“ LoadLibrary”,“ GetProcAddress”和“ FreeLibrary”。 As far as I know, c# does not have a way to do a sort of Dynamic PInvoke automatically. 据我所知,C#没有办法自动执行某种动态PInvoke。 See this blog post for more info 有关更多信息,请参见此博客文章

Alternatively, you could create a C# wrapper for each of your DLLs using PInvoke and then use managed delegates to call the functions. 另外,您可以使用PInvoke为每个DLL创建一个C#包装器,然后使用托管委托来调用函数。 Then, by changing the delegate, you can call a different function (presumably in a different DLL) at runtime. 然后,通过更改委托,您可以在运行时调用其他函数(可能在其他DLL中)。 This would depend on you having a complete list of the DLLs you intend to use at compile time. 这取决于您在编译时要使用的DLL的完整列表。 It is quite a bit more robust than the first option though. 但是,它比第一种方法更健壮。 It's also a thousand times easier to let the runtime handle all of the marshaling for you. 让运行时为您处理所有封送处理也要容易上千倍。 See this MSDN article for more information. 有关更多信息,请参见此MSDN文章

If they are already in C++, I would opt to write the managed assembly in C++. 如果它们已经在C ++中,我将选择用C ++编写托管程序集。
This walkthrough could be a starting point. 演练可能是一个起点。 Especially the C++ guy does not need to learn C#. 特别是C ++的人不需要学习C#。
P/Invoke is a little bit slower, but the deeper issue is for you the version management as P/Invoke will lead to runtime-exceptions and not compile errors in case of changes. P / Invoke稍慢一些,但更深的问题是版本管理,因为P / Invoke将导致运行时异常,并且在发生更改时不会编译错误。

您可以使用Microsoft提供的externDLLImport类的工具,有关更多详细信息,请单击此处此处

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

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