C++/CLI托管字符串与非托管char数组的转换
时间:2011-01-11 来源:sunrack
显示行号 复制代码 ? 这是一段程序代码。
-
// CLR.Dll.h
-
-
#pragma once
-
#include "string.h"
-
-
-
using namespace System;
-
using namespace System::Runtime::InteropServices;
-
namespace CLRDll {
-
public ref class DllClass
-
{
-
public:
-
String^ FunctionTest(String^ input)
-
{
-
char* inputChar = ManagedString2UnmanagedStringA(input);
-
//call native c++ function...
-
inputChar[0] = 'A';
-
String^ result = UnmanagedStringA2ManagedString(inputChar);
-
return result;
-
}
-
private:
-
//将?非?托D管ü的?ANSI字?符?串?转a换?成é托D管ü字?符?串?
-
String^ UnmanagedStringA2ManagedString(char* pIn)
-
{
-
return Marshal::PtrToStringAnsi(static_cast<IntPtr>(pIn));
-
}
-
//将?托D管ü字?符?串?转a换?成é非?托D管ü的?ANSI字?符?串?
-
char* ManagedString2UnmanagedStringA(String^ strIn)
-
{
-
IntPtr ip = Marshal::StringToHGlobalAnsi(strIn);
-
const char* pTemp = static_cast<const char*>(ip.ToPointer());
-
char *pOut = new char[strlen(pTemp)+1];
-
strcpy(pOut, pTemp);
-
Marshal::FreeHGlobal(ip);
-
return pOut;
-
}
-
};
-
}
C#
显示行号 复制代码 ? 这是一段程序代码。
-
public void RunTest()
-
{
-
DllClass curDllClass = new DllClass();
-
string input = "test";
-
string output = curDllClass.FunctionTest(input);
-
}
相关阅读 更多 +