lundi 29 juin 2015

native C++ use C# DLL via CLR wrapper


Trying to make a minimal code sample of calling a C# DLL from Native C++. The most straightforward method seems to be via CLR DLL wrapper.

C# DLL file (want to call this from native C++):

namespace CSharpDLL
{
    public static class CSharpFunctions
    {
        static bool myBool = false;

        public static bool GetBool() { return myBool; }
        public static void SetBool(bool b) { myBool = b; }
    }
}

CLR DLL header file (wraps the C#):

#pragma once
using namespace System;

namespace ClrDLL 
{
    public ref class ClrFunctions
    {
        public:

        bool GetBool();
        void SetBool(bool b);
    };
}

CLR DLL class file (wraps the C#):

#include "stdafx.h"
#include "ClrDLL.h"

#using <CSharpDLL.dll>  // C# DLL
using namespace CSharpDLL; // C# DLL namespace
using namespace ClrDLL;
using namespace System;

bool ClrFunctions::GetBool()
{
    return CSharpFunctions::GetBool();
}

void ClrFunctions::SetBool(bool b)
{
    CSharpFunctions::SetBool(b);
}

And finally a Win32 Console Project test file (attempts to call C# from native C++):

#include "stdafx.h"
#include <iostream>
#include "..\ClrDll\ClrDll.h"

using namespace std;
using namespace ClrDLL;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "This program demonstrates using a C# DLL in C++" << endl;
    cout << endl;

    // instance of clr dll class
    ClrFunctions clrFunctions; 

    // get bool example
    cout << "Get bool from C# DLL: ";
    bool b = clrFunctions.GetBool();
    cout << boolalpha << b << endl;

    // done!
    cout << "Hit any key to exit!";
    getchar();
    return 0;
}

Having two specific problems:

  • The CLR Wrapper compiles but does not output a DLL or LIB file
  • The test program fails to compile because the DLL Wrapper Header has "using namespace System;" and that requires CLR flag (which I cannot use)

Aucun commentaire:

Enregistrer un commentaire