So what is PInvoke ?
Platform Invocation Services (PInvoke) allows managed code (code which runs in Microsoft CLR) to call unmanaged functions (code compiled directly to Machine Language) that are implemented in a DLL.
The advantage of using PInvoke in my case is that, C++ DLLs compiled to machine Language runs much faster than compiled to CLR.
How to use PInvoke – Basics
Let's assume you have a function int getValue(char c) { ... } in a C++ App. First you have to change and wrap like below.
#ifdef __cplusplus
extern
"C" {
#endif
__declspec(dllexport) int getValue(char c)
{
//some code
return 0;
}
#ifdef __cplusplus
};
#endif
Now recompile the program as a DLL and we are ready to call this function from C#.
So in your C# Application, first include
using System.Runtime.InteropServices;
Then add below line in the class file.
[DllImport("YourDllName.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int getValue(char c);
After that you can call that function just like calling any C# function.
Eg: int i = getValue('a');
How to get a C++ struct from C#
Let's assume that you have a C++ function which returns a structure. And you need to get the returned C++ structure from the C# code. Here is how you should do it.
In the C++ code, the structure should look like this.
#pragma
pack(push, 8)
struct Location {
int x;
int y;
};
#pragma
pack(pop)
And assume that the C++ function (which returns the structure) looks like below,
__declspec(dllexport) Location getLocation(int a)
{
Location loc;
loc.x = 10;
loc.y = 20;
return loc;
}
So in the C# code, it should look like,
[DllImport("YourDllName.dll", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Struct)]
public static extern MyLocation startProcessing(int a);
[StructLayout(LayoutKind.Sequential)]
public struct MyLocation
{
public int x;
public int y;
}
Then you can call the C++ methid in C# like,
MyLocation loc = startProcessing(10);
Reference
http://msdn.microsoft.com/en-us/library/ms235282.aspx
http://msdn.microsoft.com/en-us/library/ms973872.aspx
http://msdn.microsoft.com/en-us/library/aa712982.aspx
http://msdn.microsoft.com/en-us/library/aa446536.aspx
http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
http://msdn.microsoft.com/en-us/library/ms973872.aspx
http://msdn.microsoft.com/en-us/library/aa712982.aspx
http://msdn.microsoft.com/en-us/library/aa446536.aspx
http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
If you have any issues, please add a comment so that I can help you as I can !
4 comments:
why not:)
Superb blog post, I have book marked this internet site so ideally I’ll see much more on this subject in the foreseeable future!
If you could e-mail me with a few suggestions on just how you made your blog look this excellent, I would be grateful.
What a great resource!
Post a Comment