2017-08-28 32 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"; 
}