Sunday, October 5, 2014

How to reference C++ dll (VS 2013) from C# ( VS 2013 )

In the last post, I shared how to reference C++ dll from Java via JNI. If you have interest you can click here. An this post, I will like to share the C++ dll which is referenced by C# in VS 2013. The programming logic is almost the same, it's input string and output string but just change the running language from Java to C#. However the steps are easier. Here are the major steps.


  1. Composed C++ *.dll.
  2. Composed C# *.cs
  3. Executed C# and Debug into C++ *.dll

Again, there has other ways to using C++ *.dll in C#, however I share here is the way that works for me. Please check it and share any comment with this post.

1. Compose C++ *.dll
The example we design is input string and return string, Here is the standard guide from Microsoft to create a dll project (Walkthrough: Creating and Using a Dynamic Link Library (C++)). Here my project calls "clsGetStringDll"

a. right click add new header file call "clsGetStringDll.h" and place the header code as below.
// clsGetStringDll.h

#pragma once


namespace clsGetStringDll

{
class clsGetString
{
public:
const char *GetStringCPlusPlus(const char *strBuffer);
};
}

b. click clsGetStringDll.cpp and place the code as below.
// clsGetStringDll.cpp : Defines the exported functions for the DLL application.

#include "stdafx.h"

#include <iostream>
#include "clsGetStringDll.h"

#include <string>


using namespace std;


string strReturn;

extern "C"{
namespace clsGetStringDll
{
__declspec(dllexport) const char *GetStringCPlusPlus(const char *strBuffer)
{
const char *chrReturn = (const char *)strBuffer;
strReturn = chrReturn;
MessageBox(0, strReturn.c_str(), NULL, MB_ICONINFORMATION);
return strReturn.c_str();
}
}
}

c. right click project -- > property --> configuration property --> project default --> character set  change to "Use Multi-Byte Character Set", because i would like to show up in C++ messagebox.

d. right click porjet and build / rebuild then you should know where is your dll location at "output" window.

e.g:
1>------ Rebuild All started: Project: clsGetStringDll, Configuration: Debug Win32 ------
1>  stdafx.cpp
1>  clsGetStringDll.cpp
1>  dllmain.cpp
1>     Creating library C:\Users\xxx\Documents\Visual Studio 2013\Projects\clsGetStringDll\Debug\clsGetStringDll.lib and object C:\Users\xxx\Documents\Visual Studio 2013\Projects\clsGetStringDll\Debug\clsGetStringDll.exp
1>  clsGetStringDll.vcxproj -> C:\Users\xxx\Documents\Visual Studio 2013\Projects\clsGetStringDll\Debug\clsGetStringDll.dll
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

2. Composed C# *.cs
right click solution and create a new C# console application project. here I name my C# project as consoleGetStringCSharp. Then place the code as below into your *.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Runtime.InteropServices;


namespace consoleGetStringCSharp

{
    public static class DllHelper
    {
        [DllImport("c:\\users\\xxx\\documents\\visual studio 2013\\Projects\\clsGetStringDll\\Debug\\clsGetStringDll.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetStringCPlusPlus")]
        private static extern IntPtr GetStringCPlusPlus(StringBuilder strbfFilePath);
        public static string GetStringCSharp(string strInput)
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append(strInput);
            return Marshal.PtrToStringAnsi(GetStringCPlusPlus(buffer));
        }

        static void Main(string[] args)

        {
            Console.WriteLine("Start");
            string strReturn = DllHelper.GetStringCSharp("Hello World");
            Console.WriteLine(strReturn);
            Console.WriteLine("OK");
        }
    }
}

3. Right click C# project as start project. If you are in debug mode you can set up breakpoint at the line you would like to stop. Then click "Start" green button on the menu tool bar. you would run the the C# code and reference the C++ dll. Input the string ( char pointer ) , lunch C++ messagebox, then return the string result back to C#.

Hope it's help and feel free to leave your comment.

No comments:

Post a Comment