【问题标题】:Exposing managed C# through C++/CLI通过 C++/CLI 公开托管 C#
【发布时间】:2017-08-30 19:29:42
【问题描述】:

我有这个用 /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 是我正在探索的内容。但我需要导出一个函数,该函数返回一个托管函数返回的字符串。

这是我最好的尝试。编译为 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";
}

【问题讨论】:

  • 是 callTest() 是通过 c++/CLI 实现的。 Java 是否可以直接调用它是另一回事。 c++/CLI 的重点是它可以从托管语言而不是非托管语言调用
  • 不知道为什么经过这么多研究和一些工作代码后它被否决了。 Java 确实使用 JNA 成功调用了exportedCall()。
  • 不是我。在这里,有一个+1。 :)

标签: c# c++ c++-cli


【解决方案1】:

这段代码是我所追求的。我已经在调试模式下执行了 .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";
}

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多