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

Exposing managed C# through C++/CLI

本文关键字:C++ CLI 通过      更新时间:2023-10-16

我用/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";
}

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