Important note

This article replaces the previous one with the same title.
Indeed the previous C++/CLI wrapper implementation had a flaw that created memory corruption.This issue has been fixed in the following implementation.
Moreover I’ve used it as an opportunity to greatly enhance the content, especially the description of the C++/CLI wrapper implementation, design rationales being now included.

Update note

The article has been updated on the 19th of June 2016 to integrate 3 fixes:

the YahooAPIWrapper‘s destructor is correctly declared in the header file to avoid memory leaks,

the YahooAPIWrapper‘s definition/cpp file does not redefine the class and the __declspec(dllexport) metadata has been moved to the header file to avoid compilation errors,

the YahooAPIWrapper‘s and native C++ program’s implementations have been updated to take into account the new fields names of Yahoo API to avoid runtime exceptions.

Introduction

When it comes to software development in a professional environment, heterogeneity is the rule not the exception: you often need to interact with systems developed with other technologies.

I’ve been recently faced with such a situation: a team that uses only native C++ needed to retrieve data using the object-oriented API of another team that develops only in .Net with C#.
This is a relatively uncommon scenario (just look at the number of articles on the subject), the standard case being new systems based on the .Net platform, developed in C# or VB.Net, needing to interact with legacy systems developed in native C++.

I’ve used the C++/CLI platform due to its unique ability to mix managed (.Net) and native code in one place and is then the ideal tool for building bridges between these two worlds using simple wrappers: the native face of the wrapper can be consumed by the legacy components and its managed face can directly use the C# API.

In this article I’ll illustrate how I’ve tackled the issue by building a simple C++/CLI wrapper, using a similar use-case: market-data retrieval from Yahoo.

the “__declspec(dllexport)” metadata that asks the compiler to publicly export the whole interface of the class and to generate a “.lib“ file we’ll use to link the native C++ program with the C++/CLI DLL

the forward declaration of the “YahooAPIWrapperPrivate” class, needed so that the compiler knows “YahooAPIWrapperPrivate” refers to some class defined somewhere; where it is and what it is is irrelevant for the compiler at this stage, it only needs to know it has to emit code that allocates a memory area whose size is the size of any pointer on this platform.

the hats “^” represent managed references, i.e. they point to managed objects (like “System::String“) allocated on the managed heap; they are to managed objects what native pointers are to native objects allocated on the native heap

the “gcnew” operator is used for allocating objects on the managed heap, whereas the “new” operator allocates only on the native heap

“cli::array” is the C++/CLI representation of a managed array

“auto_gcroot” is a wrapper around a managed reference: you can’t directly embed a managed reference inside a native type especially because the way memory is handled in the native and managed worlds is quite different; moreover, compared to “gcroot“, which too avoid explicit management like pinning, “auto_gcroot” is automatically disposed when going out of scope

the “StringToHGlobalAnsi” method converts a managed “System::String” which is made of UTF-16 chars to an array of ANSI chars it allocates on the native heap; it returns a pointer to this array as an “IntPtr” which is a managed wrapper around a native pointer that we obtain with the “ToPointer” method as a “void*“

moreover you may wonder why we use “const char*” instead of “std::string“: because publicly exposing STL types is brittle as their implementation could differ from vendor to vendor and even between different versions from the same vendor

Well, after all, there is quite a bunch of things to explain. 🙂
But if you use C++/CLI on a regular basis you’ll quickly become familiar with this at first cryptic stuff.

Design rationales

You may have one more question: why the gcroot field has been isolated in its own structure?
First you should know that in native C++ you must declare all the members of a type, including the private part.
This may seem strange to C# programmers, because in C# the private part is hidden; but for native C++, header files are more than a simple description of the interface of the types, they describe their memory structure too, then all the information must be available to the calling code so that it is able to correctly allocate the memory for the instances of the types, otherwise you’ll get memory corruption (believe me you don’t want to live such a situation ;)).

But in that case, why not simply add the gcroot field to the class declaration?
Because “gcroot” is pure C++/CLI stuff that has no sense for native C++ so your code won’t even compile; moreover, even if it compiled, this would be an ugly leak of the abstraction we’re trying to build.
With this design we’ve hidden all the C++/CLI stuff inside the “YahooAPIWrapperPrivate” structure so that our wrapper has an interface compatible with native C++.
Finally, I’ve later discovered that I’ve only reinvented the wheel: the PIMPL principle used in native C++ development; so it seems like one more compelling argument in favor of this design.

OK for using an additional structure, but why a pointer to the structure instead of an instance?
Because as I’ve said you must fully describe the memory layout of your types, this includes the memory layout of objects inlined into the types, so here the compiler of the native C++ code should have to know the layout of the “YahooAPIWrapperPrivate” type too, so it should know about … gcroot.
We have not this issue with pointers because they all have the same size; indeed the values of pointers are memory addresses: their size depends only on the platform (Intel 8088 (16 bits), x86/IA-32 (32 bits), IA-64 (64 bits)…); then the compiler can allocate a fixed amount of memory per pointer without having to worry about the objects pointed to.

As you can see, from the point of view of the native C++ application, things are transparent (be it the source code or the compilation process), there is no trace of any .Net stuff (except the name of the wrapper I’ve deliberately made explicit), just a plain old native C++ API.

Execution

Conclusion

As you’ve seen, using C++/CLI wrappers for native to managed interop is rather straightforward, the only difficulty being the plumbing code necessary for converting to and from managed types.
The other way around, that is managed to native interop, is almost identical except that you’ll wrap native objects and that the called side will be managed and the calling side will be native.

Though wrapping with C++/CLI is quite simple it remains a tedious and error-prone process: imagine if you need to export dozens or more managed classes!
You could of course factorize the repetitive code, like conversions, by building helpers but you’ll still need to implement the classes’ structures by-hand, so unless you have few types you should not go down this path.

Fortunately there is tools, like SWIG, that can automate the process for this kind of scenario by generating the plumbing layer; they will isolate you from a significant part of the low-level details, probably avoiding you some headaches (maybe causing others ;)), so taking the time to learn them should be worth it on the long term if you have a big project.

If you’ve used this approach in a real-life project too, I’d be really interested in hearing from you, so please let a comment with your feedback.
If you have any remark, question or suggestion feel free to let a comment as well.

Hi,
if I remember well there was an issue in the initial version of the article.
Are you using the latest version of the code?
If so can you please share your code, or a similar one that reproduce the issue?
Thanks.
Mickael

hey thanks for the reply
but I have a question Now. Yesterday i solve that problem by adding my c# project as a reference so my ques. is that .. do I need to do that(adding my c# project as a reference).

what is the extension of your file?
If you’ve used “.c” you can either:
– change it for “.cpp”
– compile with the “/Tp” (note the upper “T”) option to help “cl” understand you’re working with C++: cl /Tp test.c YahooAPIWrapper.lib

I have tried your source code and Compiled a DLL, When I tried to call the DLl from my python code it gives me a error of Method ‘GetAsk’ not found. could you please explain how can I expose the method GetAsk to the non C++ functions?

Hi Tran,
yes you can use whatever part of .Net you want, even some WPF. 😉
The only thing you have to do is bridging the native code and the .Net code with the kind of plumbing described in this article.
Let me know if you have any issue…

Hi,
First, thanks for your post.
Also, do you know if it is possible to pass to a C++ function, a C# object as a parameter ? I mean in your example, lets take private static double ParseDouble(string value) function, you use a c# string as a parameter and I wanted to know if it is possible to pass a C# object like private static double ParseDouble(Object value) and interop with it in C++ dll.

Hi Romain,
yes it’s possible but is more or less complex depending on what you intend to do.
If you want to pass a structure things are relatively straightforward: http://msdn.microsoft.com/en-us/library/awbckfbz.aspx
If you want to invoke methods then you’ll have to write a C++/CLI wrapper around your C# class, it will forward the calls from the native C++ side to the managed side.
Hope this helps…

IMHO it won’t move the needle a lot, and even if you can make it works it will be far more intrusive than building a wrapper that will cleanly uncouple the two parts.
If you have a recurrent need for this kind of interop scenario you should seriously consider using SWIG to generate the plumbing.

But how you pass the value as a parameter ?
For example :
C# :
public enum A
{
VALUE_1 =0,
VALUE_2,
VALUE_3
}
and i have a function like that : void function_A(A eValue);

So if i understood , I have to do the same structure on the C++ side like that :
enum A
{
VALUE_1 = 0,
VALUE_2,
VALUE_3
};
But how can I call the function function_A ? I mean how i can use the gcnew directive in order to pass the enum ?

Ok thanks for the tips.
Anither question concerning the way to pass the parameters between the wrapper and the managed application ; when you do _private->yahooAPI->GetBid(gcnew System::String(symbol)); I think “symbol” is passed by value the a copy is done. If I use “ref” in the c# application, do you think when I call the function by the C++ application, the parameter will be passed by reference (no copy)?

Thank you for this post,
Let me try to explain what I need: I have a large project written in c++ that I would like to leave untouched. I want to replace the current, functional Win32 user interface with a new WPF module I started implementing.
I would like to encapsulate the WPF part and interact with it using SendMessage functions. I can probably write the wrapper as a Win32 window DLL to solve this. However, I wander how I can deal with the events from the WPF part. Sould I write the handlers inside the wrapper?
Thank you in advance.
Shaul Eizikovich

First, to develop your WPF UI you should use C#, don’t be tempted by developing your WPF UI in C++/CLI even if you are fluent in C++, for at least 2 reasons:
– limited WPF integration in Visual Studio (e.g. no designer support)
– a far smaller C++/CLI developer community and believe me WPF already comes with its own set of issues 🙂

Secondly you should clearly isolate the Win32 UI layer from the “business” layer and have a self-contained business project with no dependency on the UI.

Once you have a well designed native application remains the wrapping part.
The best way of tackling this depends on the number of entry-points of the C++ business layer.
If you have few entry-points:
– not object oriented: simply build a static C# wrapper that uses DllImports
– object-oriented: write a small C++/CLI wrapper
If you have more entry-points and specifically object-oriented then you should use SWIG which will produce a C# wrapper automatically.

Once you have a wrapper the communication between the two layers should be quite obvious, you simply use the wrapper from the WPF application in a transparent manner, something like:

Thank you pragmateek for your comprehensive reply.
Thinking over and over again about the project I see it now as much simpler one:
1. As you say, WPF window will be done as pure C# project using Visual Studio. I compile it as DLL.
(Q. Can one C# DLL contain all my WPF windows or do I have to create a DLL per-window?)
2. Around the WPF windows (that is, one or more DLLs) I write a C++/CLI wrapper along the lines you suggested. The wrapper does not have to be Object Oriented, so I could write it in C# as you suggested but I’m much more fluent with C++.
3. The wrapper contains a hidden Win32 window to serve as target to application’s messages.
4. The wrapper will be compiled as DLL with two interface functions: A constructor and GetWindowHandle that will return a handle to the hidden window.
5. The wrapper will handle all events from the WPF windows.

1) The WPF part is typically a full-fledged application, like was your Win32 application, not just a DLL.
This application will contain the main entry-point and all the stuff related to the UI, including all your windows.
Of course you can isolate the entry-point, the managed Main, in another project but it’s often useless if your windows are only used from this main.
2) If your functional API is not object oriented and not too big (because you really don’t want to do all the marshalling yourself) you can indeed use DllImports, something like:

3) 4) 5) Why do you want to use window message passing between your WPF UI and your native layer?
I’m obviously missing something but the WPF UI should handle events like clicks on buttons and in response interact with the legacy code through the wrapper to compute values for example.

I don’t know what’s your exact use-case but typically here is the workflow:
– the user starts the application exe file which starts the UI immediately, starting the WPF message loop (like the Win32 message loop) on the main thread
– the WPF interface displays some inputs and some action buttons
– the user fills in the inputs and clicks an action button
– the button click event’s handler reads the input and calls a method of the wrapper and it gets some new values in return
– it displays these new values on the interface.

This assume that you have implemented a strict separation of concerns in your application: as an example a “business” method like “compute_value” should not interact with the UI, be it to read or write data.

I think this is simpler to have the managed part of your application, i.e. the WPF interface, to be the “master” part, i.e. the one that will drive things.
You could do the reverse, i.e. driving your managed C#/WPF from native C++, using the technique demonstrated in this article, but this is really not the easy way. 🙂

I really appreciate your help. This is an impressive manifestation of good will!

My current project holds a large C++ executable where the UI is only one, relatively small, module. I chose to implement the CU (Control Unit) of the executable as an invisible Win32 window so that it will serve as a hub to messages from the other units, including the UI.
The UI (Currently implemented as another Win32 window) interacts with the CU through messages. I think it is a good way to separate units and to enable development of units in parallel. Anyway, this is what we’ve got.
When The application starts, it creates the modules one by one, including the UI module.
It is of course possible to reverse the order so that the UI starts the application, leaving the CU outside as a DLL or rewriting it in C++ (Compiling it with /clr is impossible since it contains and ). However, I don’t think it will be wise, especially not being a C# person.

So I tried to create a C++/CLI wrapper to my (preliminary) WPF interface and the call the wrapper constructor from a plain C++ main. This failed. I suspect that this is because I didn’t declare my main thread as STA. I probably have to do it from the wrapper, calling the WPF in a new thread. No idea as how to do it. Wish me luck.

I’m almost there. Only annoying problem with WPF binding.
My Win32 app opens a Win32 window which opens a WPF window.
Moving the WPF window around sends it coordinates to the application and the topmost window.
When I send a message to the Win32 window it processes it and calls (using your method) a method at the C# code-behind of the WPF window.
So far so good.
Here’s the problem: Since this method is not a WPF event handler it cannot effect the WPF user interface.
Here’s the entire code-behind file (My method is Set_YYY()), “EventModel” is public class EventModel : INotifyPropertyChanged

Could you give me a hint? Thank you!

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

What’s the error you get?
WPF is a framework so you have to stick with its design, otherwise yes things can quickly become complicated. 🙂
WPF is not the best tool for everything UI related, but 90% of the time it’s better than the alternatives like Winforms.

It does not compile. It says: error CS1660: Cannot convert lambda expression to type ‘System.Delegate’ because it is not a delegate type

Actually the alternative I was thinking of was Direct2D. It is pure Win32 replacement for DGI/GDI+ , it has fantastic performance but it does not support ‘controls’ natively.
You can write your own controls (I did create buttons) though.

I chose WPF because it enables you to design non-standard GUI using XAML – I hope I over come this last (hurdle) and continue with the actual development.

The reason is that without more information the C# compiler does not know to which delegate type it should map the lambda.
In the latest version of .Net there is an overload of Invoke that takes an Action so you don’t need to cast yourself, the compiler will use the correct overload.

Dear pragmateek,
The last solution compile but did not affect the UI. I stepped into it with the debugger and it did seem to do everything it should only that the textbox was not affected.
HOWEVER, I did solve the problem in a different way that has one great advantaged: It works.
You might be interested to add it to this fantastic page.
I followed this “Walkthrough” by MS: http://msdn.microsoft.com/en-us/library/ms744829(v=vs.100).aspx#communicating_with_the_page
Search for this interesting paragraph:
The simplest solution to this issue is to implement a managed class that contains a set of static fields to hold references to any managed objects that you need access to. The sample uses the WPFPageHost class to hold a reference to the WPF content, plus the initial values of a number of its properties that might be changed later by the user. This is defined in the header.
And it is simple. You create a STATIC class in the wrapper and save there a reference to your page and controls.
You can later use them as simple pointers and write data directly to the controls!
Hope you like it and THANK YOU for your help!

Hi,
thank you for all the information in the post.
I have implemented your example to use it with VS2010 and it is working just fine.
But I have a question concerning deconstructors in this example and it would be great if you can help me with that. I am wondering why the deconstructor is never called. Also, I do get a “Detected memory leaks!” information in the output when using “_CrtDumpMemoryLeaks();” with the YahooTest.cpp which referes to _private. For example:

I solved the memory leakage problem by declaring the destructor in the YahooAPIWrapper.h as follows:

public: ~YahooAPIWrapper();

With the CRT Debug Library it depends where you put the _CrtDumpMemoryLeaks(). I verified it now by using the Visual Leak Detector (http://vld.codeplex.com/) which shows me the complete callstack if memory allocation has led to a leak.

With declaring the constructor in the wrapper header file I get: “No memory leaks detected.”

So thank you again for your excellent overview of how to write a wrapper. 🙂

The “.lib” file generated by Visual Studio for C++/CLI wrapper cannot be linked statically in XE4’s C++ project (perhaps different compilers). It gives some kind of COFF linking errors.
If we need to load this Wrapper DLL dynamically in C++ code in XE4 then how can we expose the class and its member functions including the functions that create and destroy the object for this Class exposed via wrapper C++/CLI dll?
Can you provide a sample interface header for such a scenario when we need to expose and use this wrapper for C++ code in XE4.

Basically you will create a new mangling rule but one that you control to be independent of the compilers.
If you have no overloads it will be quite simple; if you have some overloads then you’ll have to decide how you distinguish them: by appending an index (DoSomething_1, DoSomething_2, …), by appending the parameters’ types (DoSomethingWith_int, DoSomethingWith_double, …) or in any other readable manner.

Approach mentioned by you looks simple and easy to follow
but I’m struggling to expose the Class or its objects to my Native XE4 C++ App.

I’m trying to Load my C++/CLI DLL in my XE4 C++ code using LoadLibrary() and then I needed access to Class and its public
functions which I believe should be made available as we have declared it as
“class __declspec(dllexport) WrapperClass”

but how do I get to the object of this class in my Native XE4 C++ code.
I saw you mentioned something like follows which I declared in my Wrapper DLL somewhat like following:
—————————————————————–
__declspec(dllexport) Wrapper *CreateObject()
{
return new Wrapper();
}
__declspec(dllexport) void DestroyObject(Wrapper *instance)
{
delete instance;
}
—————————————————————–

I’m particularly struggling with exposing of C++/CLI DLL Class, its methods and its object to my XE4 C++ DLL to be used in XE4 code. Can you please help with some sample code?

I don’t know XE4 but the C++/CLI library can be used just like you
would with a pure native C++ library.
And this is a two steps process:
– at compile time you write your code basing it on the C++ library
headers, you trust them to match existing members of the library
– at link time the linker will try to find the symbols you’ve used in
the library.
To know which symbols are exported you can run “dumpbin /exports
CppCliWrapper.dll” and you should see mangled class’ members names.

There is nothing specific to C++/CLI: the CppCliWrapper.dll library
has the same interface than any native C++ library.
The only possible issue I imagine is different mangling rules between
the CL compiler and the XE4 C++ code.
Indeed each compiler has often its own mangling rules.

So your issue is how to use ANY native C++ library from XE4 code, and
to this I have no answer but I’m sure the community forums or users
support of the vendor have the answer. 🙂

But I’m quite optimistic as chances are good they have anticipated
this kind of common needs and allowed interoperability with CL
generated C++ code.

Hope this helps, and if you have more specific questions do not hesitate to ask.

One specific thing now that I need some help with is how to Pass a parameter by Reference across Native C++ Code to C++/CLI Wrapper code (Visual Studio 2012).
Following is an example of one of my Exposed function via Warpper DLL.
DLLEXPORT int ProcessSingleRequest(void* wrapper, const char *request, char *response)
{
return reinterpret_cast(wrapper)->ProcessSingleRequest(request, response);
}

In my Wrapper class implementation of ProcessSingleRequest() I could manage to get “response” changed to the desired value that I want to return but when it returns from above exported “C” interface its reset to NULL or undefined value. What am I missing here?

My code is based on your article shared at “http://pragmateek.com/if-your-plumbing-doesnt-work-youre-just-not-using-enough-pipes/”

I’m very new to C++/CLI and I use Visual Studio (2008) rather occasionally.
But I have a job to do, so I thought your article was a godsend.
However:
If I use Visual Studio instead of command-line compiling, the wizard automatically provides namespaces when it creates a project. I’m rather surprised to see there are none in your example. I hope adding some is not going to be a problem.

I must have a completely wrong idea about what C++/CLI is about but
I’m hugely surprised to see the class keyword appear in the C++/CLI wrapper CPP file. I thought that was left to the header file in C++!
In any case I’m getting a compiler error when I try to compile a project named YahooAPIWrapper (which is defined as a library).
\YahooAPIWrapper.cpp(17) : error C2011: ‘YahooAPIWrapper’ : ‘class’ type redefinition

Hi Henri,
– Namespaces are only a tool to organize types so using one should not change anything.
I’ve ommited namespaces to keep things as simple as possible.
– Concerning the class, AFAIK in native C++ too you can both declare and define a class in the same CPP file.
Nevertheless it’s indeed cleaner to declare the class in the header file and define its members in the CPP file.
As for your error it’s probably due to a mix between this two approaches, so sticking with the best-practice you mention, i.e. declaring in the header, and including it wherever you use YahooAPIWrapper, and defining in the CPP should fix the issue.
Moreover you may need to guard against recursive inclusion of the header with a “#pragma once”.
Hope this helps. 🙂

Your article is the clearest I’ve seen on this subject, so thanks for that! I’ve compiled your source as three projects in one solution in VS 2010. It all compiled without error. When I debug, it blows up with:

Hi Donald,
this is strange, this line will simply allocate the wrapper and call its constructor which does not do crazy things.
So try to debug the YahooAPIWrapper constructor to identify which instruction is responsible for this error.
Thanks.

Glad it works. 🙂
Visual Studio should be smart enough to allow debugging both managed and unmanaged code.
I don’t remember if there was a special configuration or if you needed to attach the debugger afterward or use another trick.
This documentation may help you: http://msdn.microsoft.com/en-us/library/kbaht4dh.aspx (the setting makes sense and this is simpler than in my memory :)).

Donald,
When you say “I added a reference to YahooAPI from YahooAPIWrapper.” what exactly did you do. I’ve built my own 3 components, all compile and execute but like you when I execute
YuniqueAPIWrapper yunique;

I crash never getting to any break point, if I trace with assembly it gets buried to deep for me to follow. I should add that my test app is an MFC Dialog type app as that is what the final app will be.

I just added a console test app and it does the same thing. For configurations my test apps and the wrapper are defined as WIN32 and the C# is x86. I added a reference in the C# app to the wrapper DLL which makes no sense to me and it had no effect.

Seems like the CLR can’t load, so probably an issue with bitness.
I fear Win32 is misleading and can also generate x64 code, which is probably the case if you are on a x64 platform.
To check this you can use the dumpbin tool:

Hi Donald,
I am getting the same exception at the same line. The app is compiled as win32 console application. Can you please tell me where have you added the reference, what change did you made exactly?

The sample is working fine when the app is compiled as a console app. When I compile the app as a .DLL and call it from another routine, it blows up on this line, with an Invalid Access error deep in Windows:

There's no material difference in the code, and the YahooAPIWrapper.cpp and YahooAPI.cs are not changed at all. All code compiled with no errors, and the .DLL loads and runs up to the line that blows up. When I put it back to console, it again works fine. It's too simple to be anything very serious, but I sure can't figure this out. Thanks for your help!

Hum, strange indeed.
Is the YahooAPIWrapper constructor called?
If yes can you identify which line exactly is crashing the app inside it?
And what happens if you instead allocate the wrapper on the heap: YahooAPIWrapper* yahoo = new YahooAPIWrapper();?

Well, it’s working now. I created two projects, one console, one dll. They both worked! I copied the .dlls to my actual app, and the blowup was the same as before. In my app, the .exe calls through 3 levels of .dlls to get to your test code. When I compiled ONLY the .exe in release mode, it worked (no blowup). I haven’t pinpointed the difference between debug and release for the .exe, but it works now! Don’t know how that could possibly relate to .dlls way downstream… Progress, maybe. Thanks for your help!

Seems like a memory issue indeed, but why does it appear when creating the class…
I really don’t like this kind of situation where you lose control, and things are kind of magic.
At least it forces us to be humble because we know we can’t control and understand everything. 🙂
I only hope the issue is not in my implementation though it’s pretty basic…

I have the need to call some vb.net dlls from an unmanaged C++ app. Though I see the *fun* in writing the wrapper class by hand, I do have to deal with deadlines 🙂 You mentioned that swig automates this plumbing step. Can you eloborate on this? As far as I can tell, swig only works with C/C++ header files. How do you get it to plumb managed vb or c# code?

Do you really need to export all the types of the VB.Net library?
You should enumerate the “services” you will need from the library and only expose entry-points for them, which should considerably reduce the development effort.
Note that you could develop these high-level services with C# which interoperates seamlessly with VB.Net.
C# is a better long-term choice than VB.Net and easier to understand if you are a C++ developer.

If you really need to use the entire object model then your best bet is probably COM interop which is supported by Visual C++.

Could you tell us more about the role of this VB.Net library, and which functions you’d like to leverage from the native C++ side?
Because depending on them there is plenty of more specific solutions.

Short history: We have 2 vendor apps. One is .Net based and the support/development team chose to use vb.net at the time (~2006, they were mostly vb6 guys anyway). That has been the defacto language since (I’ll leave the politics out as to why they won’t move to C#). The other app is C++ based with far fewer developers. I would like to take advantage of all the helper classes (oracle wrappers, application interface wrappers, custom sql queueing, etc) that have been developed using vb.net instead of reimplementing them in C++. Exposing them via COM is the normal mode, but we have several processes that require a lot interactive interactions (sql queries, etc) and the COM interop layer slows that process down a bit. I’d like to compare the performance between COM and C++/CLI.

Ah, I just re-read your section regarding swig. You were talking about managed to unmanaged plumbing, doh!

While I’m tinkering with creating this wrapper class, how do I handle dll’s with multiple classes defined? For example, I have a project called MyAccess and it’s build time artifact is called MyAccess.dll. Within that project, there are 3 classes: MyConnection, MyReader and MyAttribute. I’ve tried to follow your example, but I’m getting compile errors.

Regarding namespaces, I don’t see any explicit namespaces declared on the vb side. If I use the following code:#using "MyAccess.dll"
#include
using namespace System::Runtime::InteropServices; // Marshal
using namespace MyAccess;

Thanks for this great article! It is very very helpful. I am trying to write a windbg extension(c++ dll) which needs to take advantage of some Thirdparty C# program. I learned the way you did, got a demo work. But also run into some problem. I tried to change the return type as string instead of const char*, got the crash in the windbg UI, maybe it is because the STL compatible issue as you mentioned?
“moreover you may wonder why we use “const char*” instead of “std::string“: because publicly exposing STL types is brittle as their implementation could differ from vendor to vendor and even between different versions from the same vendor”.

I also plan to return some STL containers like vector, map. Do you have any workarounds? Do we have to stick to the primitive data types? Or we can send the container ref as an argument. I am just thinking about it, haven’t tested it yet.

And yes I can confirm that exposing STL types is definitely a dangerous practice that can cause a number of unexpected behaviors; but not sure the issue you have is one of them.

AFAIK there is no plug-and-play workaround but if you want to control your public API you can create some alternatives for the types you intend to use, that are safe to transfer across the API boundaries.

For strings using char * is a standard practice, as well as using arrays instead of vectors.
For the map you could create a class with two arrays: one with the keys, another with the values, or represent it as an array of key-value pairs.
Either use a known convention if you can find one or the simplest implementation for your special case, so that on the calling side converting between them and standard C++ types is easy.

Thank you for the advice. I tried to pass by reference, and this time I found it retrieved nothing instead of crashing. So I guess it might be some memory issue. But both ways work correctly in an exe I wrote for test. I am still shooting in the dark. I guess maybe my extension is based on COM that’s why it happens. I don’t know the internal mechanism. My assumption is based on that’s the only difference I know between the extension dll and the my test exe.

If you throw COM into the equation you’re really asking for troubles. 😉
More seriously if you are well versed in COM you may try to expose what you want from the .Net/C# stuff via COM, as it is a “standard” platform with, AFAIK, well defined types.

Makes sense. Actually i gave up both. As I found the C# exe needs the app.config at runtime to do the basicbinding. It probably would take another amount of time to get around it. I switched to python. Now the feature is done. Though I am not able to make interop work. It is a good experience. Thanks again!

Thanks for your feedback Stanley.
Python is definitely a magic tool.
I’m always amazed of this kind of “success stories” : can’t do it with C++/Java/C#… done it with Python.
I hope one day I’ll have a closer look at this strange creature. 🙂

I guess the YahooAPI managed project correctly generates the YahooAPI.dll assembly…
Have you tried to put this assembly in the same folder as your C++/CLI wrapper source file?
If it’s still broken in VS then try to compile using the command line, this is the safest way to check if there is a “true” issue or if this is just some VS glitch.

Hi pragmateek,
thank you for your great web-site and helping.
I’ve found my mistake: it’s necessary to #include “stdafx.h” before #using “YahooAPI.dll”.
Incidentally #1: in your ZIP, there is no destructor of ~YahooAPIWrapper.
Incidentally #2: I’ve done a small improvement in YahooAPIWrapper.h:
#ifdef DLL
#define DLLEXP __declspec(dllexport)
#else
#define DLLEXP
#endif
class DLLEXP YahooAPIWrapper
{…}
So I can include YahooAPIWrapper.h in YahooAPIWrapper.cpp (where I set the define DLL) and in test.cpp. So I’ve only ONE definition of the class YahooAPIWrapper in YahooAPIWrapper.h and not a second definition in YahooAPIWrapper.cpp.

Works perfect from C++. Can I use this wrapper from Delphi? If so, then how? Just calling external library gives an error “entry point not found”. Dllexportviewer shows that export functions have quite strange names.
Thanks!

The article you point to was more of a proof of concept, you should avoid using so many layers, this would be a nightmare to maintain.
I think COM is your best bet because on the .Net side the COM interop layer is well implemented and using .Net components through COM, e.g. from VBA (check my other articles), is (almost) a breeze.
To be sure this is the best choice you should ask Delphi experts but I’d be surprised if there was other serious alternatives…

Can you please give an example of how to passing arrays as argument?
I have an VC++ MFC program, and I want to call a function in c# dll like:
int LoadCodes(out int numData, out long[] Bcols, out float[] Codes, out string[] Names, out string[] ShortNames). Can you give me some advice please? Thanks!

This is a wonderful article and have been trying to add it to my attempt at wrapping the TFS API. I am still struggling a bit to manage even the connection. Hopefully I can get some suggestion or tips from you please.
The idea is to use TFS API in a C++ (QT5) project.

Thanks for the feedback Vivian.
I don’t know QT but as it is native C++ there should be no specific stuff.
The C++/CLI wrapper is a pure native C++ component that should integrate seamlessly in your QT project.
Which issue(s) do you have?

New to all of this but I’m trying to setup a project via VS2013. Using the CLR Library project setup and attempting to define the header file I’m a bit perplexed on how to define the header. Would it be possible for someone to show the header file (YahooAPIWrapper.h) setup and I’ll try to go from there with the cpp.

The main difference is his ILBridge_CppCliWrapper_Calculator has the gcroot member
private, not public, and so he has only simple wrapper functions in the NativeExport class rather than directly accessing the gcroot member from that class and having the actual code there too. I think this is a general question about how best to do PIMPL (e.g. http://www.gotw.ca/gotw/024.htm)
Maybe an advantage of Sasha’s way is that you can ensure the NativeExport class is truly native only because you compile it with #pragma unmanaged?

Using CLI to go the other direction (from C++ to .NET) doesn’t require the extra layer of indirection because C# doesn’t require #including a class declaration header file in the same way as in native C++ to use a class.

It was helpful to have yours as a second example, with the discussion about auto_gcroot and design Q&As. Thanks.

Hi Pragmateek,
I’ve been reading your blog with great interest.
I eventually need to solve a problem of a very similar nature, but am struggling with the C++ syntax. (It’s been several years, unfortunately)

As a quick synopsis, I have a C# .dll that implements a client-server object network which itself satisfies a very stringent set of rules. basically,
every object can be described as a set of (optionally read only) properties or methods
return types are either primitives (e.g. string, boolean, int, float) or objects, or arrays of primitives or objects.
parameters are either primitives or objects or arrays of primitives or objects.
thrown exceptions are also objects from within the model.
and finally, callers can create new objects from the model, or reuse existing ones.

with this in mind, here’s a fairly small (3 classes) C# example describing the model.

Hi Anil,
my C++ skills are rusty but here are some ideas for the native C++ side API:
– String -> char* (avoid std::string which is not safe across libraries boundaries)
– Stock -> Stock& or Stock*: s is a .Net reference, and equivalents in C++ are references and pointers
– Stock[] -> Stock**: in C++ we often use contiguous set of objects as arrays
On the private implementation side:
– ArrayList (you’d better use the generic type List<Stock>) -> std::vector<Stock*>

My real problem is that the ‘wrapper’ managed and un-managed h and .cpp files i created to emulate this object network aren’t compiling.
I’m running into issue attempting to pass managed references around from one object to another.
Ah well.
Thanks
Anil

Thanks this has been very helpful. I do have a question as far as memory management goes. In the method GetValues who or what is responsible for free’ing the memory allocated by unmanagedValues? If the CLR’s are different from the dll and the calling exe does that pose an issue? In my case the exe is MFC C++ 6 while the dll is in C#/.NET 4/CLR 10.

Thanks for the feedback Tim.
AFAIK in a mixed context there is two heaps:
– the unmanaged one used by new in native C++,
– the managed one used by gcnew in managed C++ and by new in C#.
But there is a single process and (most often) a single CLR, so there is no issue of this kind.
The only issue you can have is differing bitnesses: e.g. 64 for the native process and 32 for the managed DLL.
If you need to manage memory you should expose an additional FreeValues method that would take care of freeing the memory it allocated on the native heap.

Now I got errors :::
1. GetAsk is not a member of ‘msclr::auto_gcroot’
2. GetBid is not a member of ‘msclr::auto_gcroot’
3. syntax error: ‘>’
4. syntax error: identifier ‘YahooAPI’
5. ‘YahooAPIWrapperPrivate’ : no appropriate default constructor available
6. binary ‘->’ : no operator found which takes a left-hand operand of type ‘msclr::auto_gcroot’ (or there is no acceptable conversion)
7. ‘YahooAPI’ : illegal use of namespace identifier in expression
8. ‘msclr::auto_gcroot’ : too few template arguments
9. IntelliSense: namespace “YahooAPI” is not a type name

Can you tell me what I am doing wrong here? And can you suggest me some articles which help to improve my concepts like this?
Thanks, this is very useful cause After two days I found this. Really this is good article.

Hi. Firstly let me thank you for the very informative article, but also for taking the time to respond to each and every comment – much appreciated!

I’m attempting to re-use your examples to wrap up my own C# DLL using VS2015, but even though I currently only have the bare framework of the C++ wrapper I am having compile problems due to the C++ reporting that my C# class is undefined.
– It seems I can’t add a C# project reference to the C++ project
– I have tried the full path in the #using statement for the DLL
– I have added the C# dll output folder to as an additional include directory and and additional #using directory.

It’s as though the class is not exposed in the C# based DLL, yet the only major difference to your own example I have noted is that my C# class is defined within a namespace (reading previous comments you have indicated this should not matter).

I am about to re-use your example code as a VS2015 solution (rather than individual files to be compiled at the command line), but I have already noted a runtime problem with your test application when build on my machine…..

Hi Paul,
so you’ve managed to compile using VS 2015?
As for your runtime error I will try a guess: maybe the data returned by Yahoo are wrong: depending on the time bid/ask can be empty I imagine.
Debugging should tell you more…

I think, you are aware about “send to” -> “mail recipient”. If not look at this image :: http://www.guidingtech.com/assets/postimages/2012/10/send-to-mail.png
I am calling dll file when user clicks on “send to” -> “mail recipient”. I sat dll path in registry and file is called perfectly. But the issue is, I want to make dll using c# code, and in c# I cannot specify entry point like c++ code – BOOL APIENTRY DllMain. So how do I call function of dll which created in C#.

Is there any way in c# to specify an entry point?

So I found that I can not specify an entry point using C# code, so I came with another solution. And the solution is, using c++ dll entry point, I will call function of c# dll. Do you have some suggestion about this?

Sorry to respond so late but I have not received any notification for your comment. :/
You can indeed use the technique shown in this article: develop your extension in C#, wrap it in a C++/CLI DLL.
I think you don’t need a native C++ DLL as the C++/CLI one should be able to expose a DllMain entry-point.

They both use Marshal::StringToHGlobalAnsi(…) to allocate unmanaged memory on the heap with the contents of the managed string. If you read the documentation on it, it is pretty clear that this heaped allocation should be explicitly freed. when your done with it i.e.

“StringToHGlobalAnsi is useful for custom marshaling or when mixing managed and unmanaged code. Because this method allocates the unmanaged memory required for a string, always free the memory by calling FreeHGlobal.”

Due to the fact that my application is passing around quite large string buffers from managed to unmanaged, these could be a source of potential large memory leaks

Do you have any ideas on how to get around this? I attempted to save this heaped memory in a private member of of the wrapper class (not private) and then call FreeHGlobal when the dtor is called but that crashed the app.

In my case, the data is not changed so I toyed with the idea of using a pin_ptr to a pass the internal ptr back but this is no good as the pin_ptr goes out of scope when you leave the managed methods scope.

Anyway, as you can tell I am a little out of my depth on this, any suggestions on this would be much appreciated.

Just a quick followup, I was able to finally get it to work by using my initial idea of persisting the IntPtr returned by StringToHGlobalASCII in a private member of my wrapper and freeing it when it is deconstructed. Not sure what was the problem the first time I tired it out.

Hey there, thanks so much for the article. First one that’s ever gotten me close to using my VB.net DLL in native C++. However…. I’m getting an error. My vb.net DLL is just an adding function ( so no need to pay attention to it… but VB.net should work as well since C# and VB work on .NET)
Here’s my Header (trying.h)
class AddWrapperPrivate;

After compiling it with the library… It just throws me another error ( god help me please) :

An unhandled exception of type ‘System.AccessViolationException’ occurred in AddingWrapper.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

More precisely:

Unhandled Exception: System.AccessViolationException : attempted to read or write protected memory. This is often an indication that other memory is corrupt. at gcroot (Add ^).. P$AAVAdd@@(gcroot(Add^)) at AddingWrapper.Adding(AddingWrapper, double* x, double* y)

let’s tackle your issues one by one:
1) The build chain bitness must be consistent: if any of the dependencies is in x86 (32-bit) your calling code must be in x86 too.
By default you’re probably using the x86 build chain with CL x86.
The linker will not consider dependencies with a different bitness as itself, hence won’t take symbols contained in them into account, hence your error.
2) In the mainx and i are pointers (variables containing memory addresses) so you must initialize them with valid addresses (owned by the process).
But you don’t need them and you should do something like that instead:

4) The runtime error is the direct consequence of point 2):
when you write double* x = 0 you say "x is pointing to the first memory address" which is an invalid address for your process;
so when you do *x you're trying to get the value stored at this invalid address and the OS logically answers you can't do that with the AccessViolationException (segmentation fault).

Hope this helps.

Tell me if you manage to get it to work or if you have any other issue.

I created a C# class library for the YahooAPI. Then I added another project containing a C++ header and source file for YahooWrapper supporting CLR. The last project consists of the test.cpp. I have a problem in the following class in the YahooWrapper:

but i have these 2 errors :
1)Error C3395 ‘clr::calculate’: __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention Line 19 of my ClassLibrary4.h
2)Error C2228 left of ‘.value_return’ must have class/struct/union ClassLibrary4.cpp Line 32 of my ClassLibrary4.cpp

Thank you for updating this article with new memory control. Lots of examples out there with managed calling native, not so many with native calling managed. I originally used the “ManWrap” stuff from ages ago and everything started breaking on win 10 and server 2012. I got that to work then XP broke. I will be updating my “ManWrap” based stuff to this. A much more straight forward approach. Hopefully that will fix the mystery problem I was having when code gated from native to CLI. I will let you know how it works out.

Hi,
Thank you for the article. Just working on the similar problem.
I am wonder about necessity __declspec(dllexport) .as far as code used as static library.
Also to proper apply pimpl idoom it looks better to use smart-pointers.
I have changed a while the code by replacing ptr to unique_ptr and make
YahooAPIWrapper class a proxy. The class functions just repeat in YahooAPIWrapperPrivate and all marshaling done inside.
So at the end it works exactly the same. Here the changes if you interesting in:

Hi Alex,
thanks for your feedback and for sharing your enhancements.
I’ve added some code markup so all code should be visible now.
Do not hesitate to fix it.
As for the __declspec(dllexport) you may be right indeed, but I’m far from being a C++ expert. 🙂

thanks for your article, It really helped me to understand this concept. I am here trying to use the existing C# API in native C++. While doing so, as you mentioned i am trying to use SWIG to generate the C++\CLI wrapper using my C# API assembly. But i couldnt see the help for the same, instead i am seeing the reverse to use C++ in C#. Can you please let know where should i find help to generate C++\CLI wrapper using my C# Code?

Hi,
thanks for the feedback. 🙂
As for SWIG indeed it won’t be a good fit for this use-case.
I fear you’ll have to write the wrappers yourself as described in this article or use some other intermediate layer that might ease the interfacing, like COM.
Indeed COM as some tools to automatically generate metadata components (type libraries TLBs) that would act like a pivot between the two worlds (.Net and C++).
The idea would be to generate the TLB from the C# code with TLBEXP and to import it on the native C++ side.
Of course COM comes with its own set of issues and craftsmanship so if you have never worked with it it’s probably not worth the trouble to learn it.
So if you have a few classes sticking with the manual C++/CLI wrapper creation is the easier and safer path.

I have a unusual issue here… I have a “c# .dll” that communicates with a SOAP Web Service, and I’m working in an old project developed in Gupta CTD 3.0… In that enviroment I can call .dll’s, but not written in C#, I’ve tried with one made in c++ and it worked… So, my question is if I can use this shown method to make a c++ .dll that communicates through a c++/cli wrapper to my c# .dll… I don’t know if I was clear enough. Thank you for the post!

Hello, thanks for the nice tutorial.
I am getting an error in my native c++ code when I define the object of YahooAPIWrapper class. I am using vs2015.

First I created C# class library in order to generate the C# dll. I copied the source code exactly as mentioned in the tutorial. Then for the C++/CLI part, I created a new C++ CLR Class library and copied the source code into YahooAPIWrapper.cpp and .h. This generates a dll and lib file. Now, I create a C++ project and include the header file in main.cpp. For including the library, I mentioned the location in “Additional Library directories” in Linker->General and also mention the lib file in Linker->Input.
Now when I run this code, I get the following error:

Hello Pragmateek,
I have used this wrapper for various projects. I am able to pass single variables such as int or string using the wrapper between c# and c++. I am currently stuck on passing byte array.

I have a c# dll for which i have made a c++cli wrapper. With this I can call the c# functions in native c++. The c# code has an image as a byte array and bitmap. I want to pass this image to native c++ code for further usage. I have checked various links on SO and it seems that there is a solution using Lockbits but I do not understand it. Is it possible for you to make a tutorial for the same or give some good sources.
Thanks

Hello Ankit,
depending on your use-case you could try to let the Bitmap operations on the C# side, and only command them from C++ through more simple method calls.
I’ve never used the Bitmap API but the MSDN sample seems similar to your use-case: Bitmap.LockBits
Except that in your case you would pass a pointer to the copied array back to C++ instead of manipulating it on the C# side.

I would just like to say, as a fellow developer/blogger and C++ wrangler, the energy and commitment you’ve put into helping each and every poster here is, without doubt, inspirational and admirable. You deserve a medal!

Loaded projects into VS 2015 (it upgraded the Wrapper), built OK but run/debug failed with
Unhandled exception at 0x75e21812 in Test.exe: 0xE0434352: 0xe0434352.
Trying to find a solution like this – calling C# code from native C++ – and nothing works