简体   繁体   中英

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#.

We have a set of DLLs written in C++, they have the same classes and same functionality, but they work differently. As an instance let's say our program converts BMP files. We have DLLs for converting BMP to JPG, BMP to PNG and so forth.

Our program which is written in C# somehow should wrap those DLLs, but not in a static way. We'd like to be able to change the DLL in use during runtime, and add new DLLs when need be (also during runtime). 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." As far as I know, c# does not have a way to do a sort of Dynamic PInvoke automatically. 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. Then, by changing the delegate, you can call a different function (presumably in a different DLL) at runtime. This would depend on you having a complete list of the DLLs you intend to use at compile time. 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.

If they are already in C++, I would opt to write the managed assembly in C++.
This walkthrough could be a starting point. Especially the C++ guy does not need to learn 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.

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

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