通过 C++/CLI 公开托管 C#

Exposing managed C# through C++/CLI

我用 /clr 编译了这个 C++/CLI 代码。

// CppBridge.cpp : Defines the entry point for the console application.


#include "stdafx.h"
#using <mscorlib.dll>


using namespace System;
using namespace EmulatorLibrary;

using namespace std;

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT const char* exportedCall()
{

    return "exportedCall";
}


public ref class DelegateCLI
{
  private:

  EmulatorDelegate^ emulatorDelegate;

  public:

  DelegateCLI() {

    emulatorDelegate = gcnew EmulatorDelegate();
  }

  String^  callTest() {

    return emulatorDelegate->test();

  }

};

可以打电话

exportedCall() 

来自 JNI 和 Java。我现在 Java 没有问题。

但现在我也需要通过公开它来调用 callTest()。方法还是C++/CLI。不是吗?我看到了对 gcroot 的引用,但没有完全理解实现这一点的过程。

如何在此 C++/CLI 层中导出 callTest()

更新 1:我找到了 https://msdn.microsoft.com/en-us/library/c320cx3h.aspx,我正在尝试破译它。

这不应该起作用。

extern "C" {
__declspec(dllexport)
    String^ exportedCall1() {
    EmulatorDelegate^ emulatorDelegate = gcnew EmulatorDelegate();
    return emulatorDelegate->test();

}
}

更新 2:https://msdn.microsoft.com/en-us/library/481fa11f(v=vs.80).aspx 是我正在探索的内容。但是我需要导出一个函数,该函数 returns 托管函数返回的字符串。

这是我最好的尝试。编译为 DLL。应该管用。正确的 ?必须测试。

 class Unmanaged {
 public:
    gcroot<String^> interopstring;
    Unmanaged() {}
 };

EXTERN_DLL_EXPORT const char* exportedInteropCall()
{

EmulatorDelegate^ emulatorDelegate = gcnew EmulatorDelegate();
Unmanaged u;
u.interopstring = emulatorDelegate->test();
return (const char*)
(Marshal::StringToHGlobalAnsi(u.interopstring)).ToPointer(); // "exportedCall";
}

这段代码正是我想要的。我已经在调试模式下执行了 .exe 并进行了测试。我能够从我的 C++/CLI 层调用 C# 代码。

class Unmanaged {
public:
gcroot<String^> interopstring;
Unmanaged() {}
};

EXTERN_DLL_EXPORT const char* exportedInteropCall()
{  
    EmulatorDelegate^ emulatorDelegate = gcnew EmulatorDelegate();
    Unmanaged u;
    u.interopstring = emulatorDelegate->test();
    return (const char*)
    (Marshal::StringToHGlobalAnsi(u.interopstring)).ToPointer(); // "exportedCall";
}