Hi,
Can anyone of you, tell me how to call c++ functions from c# program?
I have a C++ dll, in which i have some functions, now i want to call them from my c# code. Please tell me how can i do this. If possible provide me sample code n all.
Thank you in advance
Bye,
sree
Can anyone of you, tell me how to call c++ functions from c# program?
I have a C++ dll, in which i have some functions, now i want to call them from my c# code. Please tell me how can i do this. If possible provide me sample code n all.
Thank you in advance
Bye,
sree
AlanPosted Apr 2, 2008, 12:22 PM
It depends on what sort of a C++ dll it is and what kind of a function you want to call.
If it's a 'pure' managed C++ dll (written in either managed extensions or C++/CLI), then you can add simply add a reference to the dll to your C# project, instantiate its managed classes and call their functions as if they'd been written in C#.
If it's an unmanaged C++ dll which exports a number of static functions (i.e. functions which not are members of a class), then you can call these using a procedure called Platform Invoke which uses the DllImport attribute.
If it's an ATL dll (i.e COM), you should be able to access it from C# using COM interop.
It it's an MFC dll or you are otherwise wanting to access member functions of an unmanaged C++ class, then the only practical ways of doing this from C# are:
1. To recompile as a COM dll so that you can use COM interop.
2. To build an unmanaged C++ wrapper dll which wraps the member functions you want to call as static functions so that they can be called using Platform Invoke.
3. To build a 'mixed mode' managed C++ wrapper dll which wraps the unmanaged classes as managed classes so they can be used directly from C#.
If the situation you have requires Platform Invoke, then I'd read these two articles and MSDN tutorial to get a grasp of what this involves:
http://msdn2.microsoft.com/en-gb/magazine/cc164123.aspx
http://msdn2.microsoft.com/en-gb/magazine/cc163910.aspx
http://msdn2.microsoft.com/en-us/library/aa288468(VS.71).aspx
If it requires COM interop, then I'd read this MSDN tutorial:
http://msdn2.microsoft.com/en-us/library/aa645736(VS.71).aspx
Otherwise, if you can let me know what situation you have and which version of VS you're using, I'll try and find some sample code.