【发布时间】: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。 :)