原生C ++通过CLR包装器

时间:2015-06-29 20:06:42

标签: c# c++ .net dll clr

尝试编写从Native C ++调用C#DLL的最小代码示例。最简单的方法似乎是通过CLR DLL包装器。

C#DLL文件(想从本机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头文件(包装C#):

#pragma once
using namespace System;

namespace ClrDLL 
{
    public ref class ClrFunctions
    {
        public:

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

CLR DLL类文件(包装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);
}

最后是Win32控制台项目测试文件(尝试从本机C ++调用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;
}

有两个具体问题:

  • CLR Wrapper编译但不输出DLL或LIB文件
  • 测试程序无法编译,因为DLL Wrapper Header具有&#34;使用命名空间System;&#34;这需要CLR标志(我不能使用)

0 个答案:

没有答案