C#代码
using System;
using System.Collections.Generic;
using System.Text;
namespace TestClassLibrary
{
public class Test
{
public int TestAdd(int x, int y)
{
return x + y;
}
public string TestString(string str1, string str2)
{
string strb = str1 + str2;
return strb;
}
}
}
C++代码
#pragma warning (disable: 4278)
#include <iostream>
#include <Windows.h>
#include <tchar.h>
#include <vcclr.h>
#using <mscorlib.dll>
#using "..//Debug//TestClassLibrary.dll"
using namespace std;
using namespace TestClassLibrary;
using namespace System;
using namespace System::Runtime::InteropServices;
int TestInt(int, int);
char* TestString(char *pStr1, char *pStr2);
String^ UnmanagedStringA2ManagedString(char *pIn);
char* ManagedString2UnmanagedStringA(String^ strIn);
//以下为托管代码
#pragma managed
int TestInt(int x, int y)
{
Test t;
return t.TestAdd(x, y);
}
char* TestString(char *pStr1, char *pStr2)
{
Test t;
String ^str1, ^str2;
str1 = UnmanagedStringA2ManagedString(pStr1);
str2 = UnmanagedStringA2ManagedString(pStr2);
String^ s = t.TestString(str1, str2);
char *pResult = ManagedString2UnmanagedStringA(s);
return pResult;
}
//将非托管的ANSI字符串转换成托管字符串
String^ UnmanagedStringA2ManagedString(char *pIn)
{
String^ strOut = Marshal::PtrToStringAnsi(static_cast<IntPtr>(pIn));
return strOut;
}
//将托管字符串转换成非托管的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;
}
//以下为非托管代码
#pragma unmanaged
void _tmain()
{
int x(1), y(1), iResult;
char *pStr1 = "Str1.";
char *pStr2 = "Str2.";
char *pResult;
DWORD dwStart, dwEnd;
iResult = TestInt(x, y);
pResult = TestString(pStr1, pStr2);
cout<<"TestInt:/nx="<<x<<" y="<<y<<"/nresult:"<<iResult<<endl<<endl;
cout<<"TestSting:/nStr1="<<pStr1<<" Str2="<<pStr2<<"/nresult:"<<pResult<<endl;
cin>>iResult;
}
C++调用C#类库; 非托管C++字符串和托管字符串的转换
最新推荐文章于 2024-11-13 19:36:04 发布