My Twitter

Tuesday, April 06, 2010

PInvoke (Platform Invoke) in C#

Recently I had a requirement of calling some functions in a C++ DLL file which i created, via C#. I achieved it by using PInvoke.

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
"C" {

__declspec(dllexport) int getValue(char c)
        //some code
        return 0;

#ifdef __cplusplus

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.

pack(push, 8) 

struct Location {  
    int x;
    int y;

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);

And our own C# struct Type  - MyLocation, to which we bind the returned data, should look like below.

public struct MyLocation 

    public int x;
    public int y;


Then you can call the C++ methid in C# like,  

MyLocation loc = startProcessing(10); 


If you have any issues, please add a comment so that I can help you as I can !


Anonymous said...

why not:)

Anonymous said...

Superb blog post, I have book marked this internet site so ideally I’ll see much more on this subject in the foreseeable future!

Anonymous said...

If you could e-mail me with a few suggestions on just how you made your blog look this excellent, I would be grateful.

Anonymous said...

What a great resource!