簡體   English   中英

如何將字符串從 C++/CLI 方法返回到調用它的非托管 C++

[英]How can I return a string from a C++/CLI method back to unmanaged C++ that calls it

我試圖弄清楚如何將字符串值從 C++/CLI 方法返回到調用它的非托管 C++。 在我當前的實現中,我有一個字符串存儲在(托管)C++/CLI 方法中的本地 String ^ 變量中,我喜歡該方法返回到調用它的非托管 C++ 程序。 如果使用 String ^ 變量不是一個好的選擇,那么哪種構造/類型會更好? 請注意,我省略了 C# 方法將字符串值返回給 C++/CLI 方法的部分,因為這不是問題。

我正在使用 VS2017。

代碼示例 - 為簡單起見,代碼已減少。

非托管 C++ -----------------------------

_declspec(dllexport) void GetMyString();

int main()
{
    GetMyString();
}

(托管)C++/CLI -------------------------

__declspec(dllexport) String GetMyString()
{
    String ^ sValue = "Return this string";
    return (sValue);
}

任何幫助是極大的贊賞。 提前致謝。

您不能將String ^返回給 c++,因為它不會識別它。 雖然有一些使用 InteropServices 的轉換。 來自微軟

using namespace System;

void MarshalString ( String ^ s, std::string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars =
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

我最終在托管 C++ 方法中將 System::String^ 轉換為 std::string,將后者返回給非托管 C++ 調用者。


托管 C++ 文件摘錄:

#include <msclr\marshal_cppstd.h>

__declspec(dllexport) std::string MyManagedCppFn()
{
    System::String^ managed = "test";
    std::string unmanaged2 = msclr::interop::marshal_as<std::string>(managed);
    return unmanaged2;
}

非托管 C++ 文件摘錄:

_declspec(dllexport) std::string MyMangedCppFn();

std::string jjj = MyMangedCppFn();    // call Managed C++ fn

歸功於 tragomaskhalosJuozas Kontvainis對一個詢問如何將 System::String^ 轉換為 std::string 的 stackoverflow 問題的回答/編輯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM