在 C++/CLI (Managed C++) 專案中,從 Windows Forms 的 TextBox 讀取用戶輸入並在原生 C++ 邏輯層 (.cpp) 使用,涉及托管與非托管代碼互操作。
// Form1.h (托管類)
private: System::Void btnSubmit_Click(System::Object^ sender, System::EventArgs^ e) {
String^ managedStr = this->textBox1->Text; // 獲取 .NET String^
// 轉為原生 std::string 或 const char*
std::string nativeStr = msclr::interop::marshal_as(managedStr);
// 調用原生邏輯
NativeLogic::processInput(nativeStr);
}
// NativeLogic.h (純 C++ 標頭)
#pragma once
#include
namespace NativeLogic {
void processInput(const std::string& input);
}
// NativeLogic.cpp
#include "NativeLogic.h"
void NativeLogic::processInput(const std::string& input) {
// 這裡可以直接用 input 做純 C++ 邏輯
std::cout << "收到: " << input << std::endl;
}
#include System::String^ → std::string:marshal_as(managedStr) std::string → System::String^:gcnew String(nativeStr.c_str())若邏輯簡單,無需拆分 .cpp,直接在 Form1.h 的托管類內編寫 C++/CLI 代碼即可,避免跨邊界轉換開銷。
/clr。marshal_as 可能丟失字符,建議全鏈路用 std::wstring 或 System::String^ 穿透。掌握 msclr::interop::marshal_as,即可在 C++/CLI 專案中優雅實現 UI 與邏輯分離。