Statically linking a C++ library to a C# process using CLI or any other way

若如初见. 提交于 2019-12-24 01:55:42

问题


Is it possible to take a static library written in C++ and somehow integrate it into a .NET process in a way that the .NET process will be integrated with the lib into one exe file?
What I mean is that I know I can invoke a c++ DLL from within a C# process but the user will still have to have the C++ DLL, but is it possible to use a lib instead of a DLL?(this way the user won't even know that the exe uses my library). and if it is possible, how?


回答1:


Unique among other managed languages, C++ allows for mixed mode - a combination of managed (C++/CLI) and native C++ within the same compilation unit (dll/exe/lib), with calls back and forth. Maybe you can leverage that, create a kind of a glue layer. I've never tried though.

The key is the /clr compiler switch - you apply it to some files in the project but not others. Then you create some classes/functions as managed. The unmanaged bits can see them and call them, and vice versa. Passing primitive types around is done transparently, for strings there's some marshaling trickery. I'll be able to post more on Monday.

EDIT: seems like some deep magic would be required. Not on the mixed C++ side - on the linking the result to C# side. The Visual Studio IDE does not readily support the scenario, you see. Chances are, the regular build process won't be of any use.

EDIT2: you can compile your C++ bits to a .netmodule by specifying a /LN command line option to the compiler and /NOASSEMBLY to a linker. Now, to link that to the C# exe...




回答2:


I did something like that with visual 2008 (I don't know if it's still possible with newer versions of VC). So it IS possible. In my experience you can only mix native C++ with managed C++ though, not C#. To do so, I simply created a solution containing (in my case) several libraries written in native C++, create an exe project in managed C++ and added dependencies on the projects. You will need to write some wrapping managed C++ classes though as you cannot mix directly a native type in a managed class. (you will have some compilation error like "error C4368: cannot define 'nativeVar' as a member of managed 'ManagedClass': mixed types are not supported".

I don't know why you want to use .NET with your library, personally I wanted to use the .NET interface, and even if it worked for me, the mix has been a big pain in my back and if I had to do it again I would go with all native C++ with MFC, or GUI library.




回答3:


No, this is wholly impossible. Mixed mode is banned in C++/CLI now- every bit of code is either wholly .NET or wholly native, and the only way to cross the boundary is through P/Invoke and a DLL.



来源:https://stackoverflow.com/questions/12552951/statically-linking-a-c-library-to-a-c-sharp-process-using-cli-or-any-other-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!