C++调用C#类库; 非托管C++字符串和托管字符串的转换

5 篇文章 0 订阅

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;   
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值