一 實(shí)例 (代碼下載
http://www.shnenglu.com/Files/mzty/SystemStringAndNativeString.rar)
nativeclass.h
#pragma once

#include <string>
#include <iostream>

class NativeClass


{
public:
NativeClass(std::wstring name);
void PrintSelf();

private:
std::wstring m_strName;
};

nativeclass.cpp
#include "stdafx.h"
#include "NativeClass.h"

NativeClass::NativeClass(std::wstring name)


{
m_strName = name;
}
void NativeClass::PrintSelf()


{
std::wcout << "NativeClass: " << m_strName << std::endl;
}
refclass.h
#pragma once

public ref class RefClass


{
public:
RefClass(System::String^ name);
void PrintSelf();

private:
System::String^ m_strName;
};
refclass.cpp
#include "stdafx.h"
#include "RefClass.h"

RefClass::RefClass(System::String^ name)


{
m_strName = name;
}
void RefClass::PrintSelf()


{
System::Console::WriteLine("RefClass {0}", m_strName);
}
調(diào)用代碼:
// SystemStringAndNativeString.cpp : main project file.

#include "stdafx.h"
#include "NativeClass.h"
#include "RefClass.h"

#include <windows.h>
#include <vcclr.h>

using namespace System;

int main(array<System::String ^> ^args)


{
std::wstring nativeName = L"NativeName";
String^ refName = gcnew String("refName");

NativeClass nativeClass(nativeName);
nativeClass.PrintSelf();
pin_ptr<const wchar_t> tempNativePointer = PtrToStringChars(refName);
NativeClass nativeClass2(tempNativePointer);
nativeClass2.PrintSelf();

RefClass^ refClass = gcnew RefClass(refName);
refClass->PrintSelf();
String^ tempRefName = gcnew String(nativeName.c_str());
RefClass^ refClass2 = gcnew RefClass(tempRefName);
refClass2->PrintSelf();

return 0;
}
二 參考
http://www.cnblogs.com/tallman/archive/2007/07/25/831247.html轉(zhuǎn)向.NET后,手頭上往往仍有舊的模塊要重用。也許這些模塊是Delphi寫的,也許是C/C++寫的,或者是其它編程語(yǔ)言……為了能把它們移植到.NET下,或者是在.NET中調(diào)用,To be or not to be, that is a question。
在這里,我筆記了幾個(gè)在工作中遇到的幾個(gè)場(chǎng)景。不過(guò),這里不包括完全使用C#來(lái)重寫原來(lái)用C++編寫的程序這種變態(tài)的需求。當(dāng)你被要求做這種事的時(shí)候,請(qǐng)三思而后行……這簡(jiǎn)直是種非人的折磨。
場(chǎng)景一:在.NET中調(diào)用WindowsAPI或DLL。
這是比較普遍的需求。一般來(lái)說(shuō),簡(jiǎn)單的函數(shù)調(diào)用,大可直接用C#/VB.NET,經(jīng)過(guò)DllImport屬性包裝出函數(shù)來(lái)調(diào)用。如:
[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
public static extern bool MoveFile(String src, String dst);
由于WindowsAPI用到的人實(shí)在是多,因此有一個(gè)專門的wiki站點(diǎn),收集這方面的資料:
http://www.pinvoke.net/,對(duì)于常用的函數(shù)甚至有完整的應(yīng)用例子和幫助。當(dāng)然,如果你有相應(yīng)的資料和例子,你也可以貢獻(xiàn)你的力量,給其它人幫助。
場(chǎng)景二:用托管C++包裝現(xiàn)有的DLL,供C#調(diào)用
當(dāng)函數(shù)的參數(shù)或返回值比較復(fù)雜,或函數(shù)比較多的時(shí)候,這種方法對(duì)與人來(lái)說(shuō),實(shí)在是一個(gè)折磨。常常這些接口和定義就要用掉幾千行的代碼,而且還不能保證是正確的。這些錯(cuò)誤往往在運(yùn)行時(shí)才能顯現(xiàn)出來(lái),甚至有些錯(cuò)誤會(huì)引起內(nèi)存泄漏,或其它更為隱蔽的錯(cuò)誤。
在這種情況下,使用C++/Managed代碼來(lái)包裝,就成了最合理的選擇。因?yàn)橥泄蹸++代碼可以直接引用原有的頭文件,直接調(diào)用非托管函數(shù),而不需要聲明。這樣,既減少了工作量,又避免引入錯(cuò)誤。缺點(diǎn)是,這種方法會(huì)增加一個(gè)DLL。
要注意的是托管字符串和非托管字符串是有區(qū)別的,并需要轉(zhuǎn)換(特別要注意的Unicode字符串和多字節(jié)字符串的轉(zhuǎn)換)。
仍以MoveFile為例吧,這樣比較簡(jiǎn)單:
#include <windows.h>
#include <vcclr.h>

using namespace System;

namespace wrapper


{

public ref class ApiWrapper
{
public:
bool static MoveFile(String ^ lpExistingFileName, String ^ lpNewFileName )

{
pin_ptr<const wchar_t> src = PtrToStringChars(lpExistingFileName);
pin_ptr<const wchar_t> dst = PtrToStringChars(lpNewFileName);
return ::MoveFile(src, dst);
}
};
}
然后在C#中,引用上面代碼生成的DLL文件,就可以直接調(diào)用了:
wrapper.ApiWrapper.MoveFile(@"c:\debug.log", @"c:\debug.txt");
假如原有的代碼是基于COM的,那么太好了,VisualStudio等IDE會(huì)自動(dòng)生成一個(gè)用于包裝的dll,供你調(diào)用。當(dāng)然因特殊需要而手工編碼的是另一回事。
場(chǎng)景三:現(xiàn)有C++原代碼,包裝后供C#調(diào)用。
C++的原代碼,實(shí)際上可以直接編譯成托管代碼。MFC也好ATL也好……這樣看起來(lái)在.NET中最強(qiáng)大的編程語(yǔ)言就是C++了:它不僅可以編寫托管程序,甚至可以將標(biāo)準(zhǔn)C++的代碼也編譯成托管程序!其實(shí)VC++最強(qiáng)大的地方不止如此,它還在于能夠編寫混合了托管和非托管的代碼的程序?。?!這樣最大的好處不僅可以將關(guān)鍵代碼直接編譯成非托管的代碼,還可以避免被反編譯。
假設(shè)現(xiàn)有C++代碼如下:

class UnmanagedClass
{
public:

LPCWSTR GetPropertyA()
{ return L"Hello!"; }

void MethodB( LPCWSTR )
{}
};
我們只要再增加一個(gè)包裝類到工程文件中:
namespace wrapper


{

public ref class ManagedClass
{
public:
// Allocate the native object on the C++ Heap via a constructor

ManagedClass() : m_Impl( new UnmanagedClass )
{}

// Deallocate the native object on a destructor

~ManagedClass()
{
delete m_Impl;
}

protected:
// Deallocate the native object on the finalizer just in case no destructor is called

!ManagedClass()
{
delete m_Impl;
}

public:

property String ^ get_PropertyA
{

String ^ get()
{
return gcnew String( m_Impl->GetPropertyA());
}
}


void MethodB( String ^ theString )
{
pin_ptr<const WCHAR> str = PtrToStringChars(theString);
m_Impl->MethodB(str);
}

private:
UnmanagedClass * m_Impl;
};
}
然后,改變編譯選項(xiàng)為“使用公共語(yǔ)言擴(kuò)展 /clr”就可以了。這樣,我們把代碼編譯成DLL文件就可以供.NET其它語(yǔ)言調(diào)用了。
最后,C#中可以象如下的代碼一樣調(diào)用C++類了:
ManagedClass mc = new ManagedClass();
mc.MethoB("Hello");
string s = mc.get_PropertyA;
場(chǎng)景四:如何在托管C++代碼中混合托管和非托管代碼
很簡(jiǎn)單,只要從#pragma unmanaged編譯指示開(kāi)始的程序,一率編譯成非托管代碼;要想恢復(fù)成托管代碼,只要使用#pragma managed就可以了。如:
#pragma unmanaged

#include <iostream>
using namespace std;

template<typename T>

void f(T t)
{
cout << t << endl;
}

#pragma managed

using namespace System;


void m(String ^ s)
{
Console::WriteLine(s);
}


void main()
{
f("Hello");
m("World");
}
生成exe文件后,用反編譯程序查看 f 函數(shù):
[PreserveSig, MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType=MethodCodeType.Native), SuppressUnmanagedCodeSecurity]
public static unsafe void modopt(CallConvCdecl) f<char const *>(sbyte modopt(IsSignUnspecifiedByte) modopt(IsConst)*);
看不到源碼,而方法屬性標(biāo)記為Unmanaged。
如果沒(méi)有加上#pragma unmanaged,反編譯得到的 f 函數(shù)為:
internal static unsafe void modopt(CallConvCdecl) f<char const *>(sbyte modopt(IsSignUnspecifiedByte) modopt(IsConst)* t)


{
std.basic_ostream<char,std::char_traits<char> >.<<(std.operator<<<struct std::char_traits<char> >(*((basic_ostream<char,std::char_traits<char> >* modopt(IsImplicitlyDereferenced)*) &__imp_std.cout), t), (basic_ostream<char,std::char_traits<char> >* modopt(IsImplicitlyDereferenced) modopt(CallConvCdecl) *(basic_ostream<char,std::char_traits<char> >* modopt(IsImplicitlyDereferenced))) __unep@?endl@std@@$$FYAAAV?$basic_ostream@DU?$char_traits@D@std@@@1@AAV21@@Z);
}
其中的函數(shù)內(nèi)容一目了然。如果你的函數(shù)沒(méi)有調(diào)用operator等不好理解的類庫(kù),那么反編譯出來(lái)的代碼簡(jiǎn)直和源碼沒(méi)差別。
開(kāi)心一刻:我只會(huì)C++不懂.NET不懂C#,怎么編寫.NET程序?
很簡(jiǎn)單,你照樣用你的C++寫你的程序,然后測(cè)試沒(méi)有錯(cuò)誤后,將編譯選項(xiàng)改為/clr,好了,Rebuild,你的程序現(xiàn)在是.NET了。
惡搞:“我想問(wèn)一下,在能將現(xiàn)有的C++代碼直接進(jìn)行封裝,被C#進(jìn)行調(diào)用,而不是去調(diào)用DLL,也就是不生成DLL,就在C#下能直接調(diào)用VC的工程源文件不?”
我想,提問(wèn)的人是不是指,現(xiàn)有c++源碼,但不想費(fèi)勁去轉(zhuǎn)換成C#源碼,但又想能與C#一起編譯。
于是我就給了一個(gè)極其變態(tài)的方法,不過(guò),個(gè)人是不建議使用這種變態(tài)的方法啊。方法如下:
1 先將C++源碼,改用CLR編譯選項(xiàng),編譯成.NET的Assembly(DLL文件)。
?。病∪缓笥胷eflector等反編譯軟件,反編譯成C#代碼,并導(dǎo)出(reflector有專門的導(dǎo)出插件)。
3 將導(dǎo)出的C#代碼,添加上新寫的C#代碼一起編譯。
這種方法生成的代碼很是恐怖,強(qiáng)烈建議不要把C++源碼就這么丟了,否則后果自負(fù)。