2016-02-17 46 views
0

我有一個本機C++ dll,我試圖從C++/cli項目調用。這裏的DLL函數從C++/cli調用std :: string參數的本地C++ dll

extern "C" 
{ 
    int DLL_EXPORT Add(std::string s1, std::string s2, std::string s3) 
    { 
    [do stuff] 
    } 
} 

下面是在C基準++/CLI:

using namespace System::Runtime::InteropServices; 
[DllImport("my_dll.dll")] 
extern "C" int Add(std::string, std::string, std::string); 

當我調用該函數,我當元帥的字符串^對象的std :: string:

Add(msclr::interop::marshal_as<std::string>(stringA), 
      msclr::interop::marshal_as<std::string>(stringB), 
      msclr::interop::marshal_as<std::string>(stringC)); 

當調用DLL時,會出現訪問衝突異常。

回答

1

是否使用相同的編譯器編譯DLL和CLI?一般來說,不同的編譯器可以有不同的定義std::string,這可能會導致錯誤。

因此,我不會推薦一般在DLL接口中使用std::string或任何編譯器特定的類型。

我想這就是你製作功能extern "C"的原因。如果它沒有extern "C"不起作用,它很可能不會工作(因爲不同的修改規則,這意味着不同的編譯器或至少不同的定義)。

在這種情況下,我寧願創建一個包含const char *指針的包裝函數。

+0

不同的編譯器。你很聰明。 – DrCocoa

+0

當使用不同的編譯器時(例如,我認爲MSVC與mingw將具有不同的std :: string定義),甚至在直接從C++調用時,它在許多情況下都不起作用。 – axalis

+4

''extern「C」'很難用'std :: string'來表達,當你考慮它時... – ebyrob

相關問題