Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to link a c++ MFC application to my C# app. The problem is the C++ app doesn't have any dll's or a lib. It uses a static library. Is there any other way to link the two applications without having to tear apart one and add it to the other?
Posted
Comments
Albert Holguin 16-Nov-11 14:09pm    
You're trying to link an application or a library? Your question doesn't make sense as it is phrased. If it's an application, then you just have to spawn an instance of the application and communicate via any built-in means (messages, pipes, shared memory, or API). If you mean linking a library, well, you usually just have to do some interfacing/wrapping as SA describes in his solution.

1 solution

What kind of link do you need? You can use your C++ library in C# project, but using C# library in C++ project is much more difficult so many even think it is impossible. Second way is quite advanced and I hope you can avoid it; first learn a first one and later ask a question on the second one if interested.

So, how to use C++ code in C#? Of course, you need to make you C++ code a DLL. If does not matter of implementation uses static library, but your C++ project should create DLL and expose some functions by exporting them. You should use primitive types or structures, but not C++ classes. Exposing C++ classes the way it can be used by .NET is also possible, but this is advanced topic, you can ask about it separately.

From this moment, you can link the methods of your native DLL in your C# project. In each case, you will need the name of DLL file and the signature of your exported methods. The technique is called P/Invoke.

You need to translate C++ signature in C# signature using available type mapping implemented in C# using default Marshalling. In more difficult cases, you need to use [MarshalAs] attribute; in even more difficult cases you might need to create custom marshaling.

Learn about P/Invoke:
http://en.wikipedia.org/wiki/PInvoke[^],
http://msdn.microsoft.com/en-us/library/Aa712982[^].

Read this CodeProject article: Essential P/Invoke[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900