2017-08-28 52 views
1

我有用/ clr编译的C++/CLI代码。通过C++/CLI公开托管C#

// 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(); 

    } 

}; 

能够从JNI和Java调用

exportedCall() 

。我目前在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"; 
} 
+0

是callTest()是通过C++/CLI。 Java是否可以直接调用它是另一回事。 C++/CLI的要点是它可以从托管语言中调用,而不是非托管语言 – MickyD

+0

不知道为什么它在经过这么多的研究和一些工作代码后被拒绝。 Java确实使用JNA成功调用了exportedCall()。 –

+0

不是我。在这里,有一个+1。 :) – MickyD

回答

0

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