Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++/CLI be used to call .NET code from native C++ applications? [closed]

I've done the other way around (calling pure C++ code from .NET) with C++/CLI, and it worked (for the most part).

How is the native-to-C++/CLI direction done?

I really don't want to use COM interop...

like image 767
Assaf Lavie Avatar asked Jun 29 '09 15:06

Assaf Lavie


2 Answers

If you have an existing native C++ app and want to avoid "polluting" it with too much CLR stuff, you can switch on the /clr flag for just one specific file and use a standard C++ header to provide an interface to it. I've done this in an old bit of code. In the header I have:

void SaveIconAsPng(void *hIcon, const wchar_t *pstrFileName);

So the rest of the program has a simple API to which it can pass an HICON and a destination filepath.

Then I have a separate source file which is the only one that has /clr switched on:

using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Imaging;
using namespace System::Drawing::Drawing2D;

#include <vcclr.h> 
#include <wchar.h>

void SaveIconAsPng(void *hIcon, const wchar_t *pstrFileName)
{
    try
    {
        Bitmap bitmap(16, 16, PixelFormat::Format32bppArgb);

        Graphics ^graphics = Graphics::FromImage(%bitmap);
        graphics->SmoothingMode = SmoothingMode::None;

        Icon ^icon = Icon::FromHandle(IntPtr(hIcon));
        graphics->DrawIcon(icon, Rectangle(0, 0, 15, 15));
        graphics->Flush();

        bitmap.Save(gcnew String(pstrFileName), ImageFormat::Png);
    }
    catch (Exception ^x)
    {
        pin_ptr<const wchar_t> unmngStr = PtrToStringChars(x->Message);
        throw widestring_error(unmngStr); // custom exception type based on std::exception
    }
}

That way I can convert HICONs into PNG files from my hairy old C++ program, but I've isolated the use of the .NET framework from the rest of the code - so if I need to be portable later, I can easily swap in a different implementation.

You could take this a stage further and put the CLR-dependent code in a separate DLL, although there would be little added value in that unless you wanted to be able to patch it separately.

like image 161
Daniel Earwicker Avatar answered Oct 05 '22 10:10

Daniel Earwicker


You can always host the CLR in your native app.

like image 39
Harper Shelby Avatar answered Oct 05 '22 09:10

Harper Shelby