尝试编写从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;
}
有两个具体问题: