一 實例 (代碼下載
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);
}
調用代碼:
// 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轉向.NET后,手頭上往往仍有舊的模塊要重用。也許這些模塊是Delphi寫的,也許是C/C++寫的,或者是其它編程語言……為了能把它們移植到.NET下,或者是在.NET中調用,To be or not to be, that is a question。
在這里,我筆記了幾個在工作中遇到的幾個場景。不過,這里不包括完全使用C#來重寫原來用C++編寫的程序這種變態的需求。當你被要求做這種事的時候,請三思而后行……這簡直是種非人的折磨。
場景一:在.NET中調用WindowsAPI或DLL。
這是比較普遍的需求。一般來說,簡單的函數調用,大可直接用C#/VB.NET,經過DllImport屬性包裝出函數來調用。如:
[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用到的人實在是多,因此有一個專門的wiki站點,收集這方面的資料:
http://www.pinvoke.net/,對于常用的函數甚至有完整的應用例子和幫助。當然,如果你有相應的資料和例子,你也可以貢獻你的力量,給其它人幫助。
場景二:用托管C++包裝現有的DLL,供C#調用
當函數的參數或返回值比較復雜,或函數比較多的時候,這種方法對與人來說,實在是一個折磨。常常這些接口和定義就要用掉幾千行的代碼,而且還不能保證是正確的。這些錯誤往往在運行時才能顯現出來,甚至有些錯誤會引起內存泄漏,或其它更為隱蔽的錯誤。
在這種情況下,使用C++/Managed代碼來包裝,就成了最合理的選擇。因為托管C++代碼可以直接引用原有的頭文件,直接調用非托管函數,而不需要聲明。這樣,既減少了工作量,又避免引入錯誤。缺點是,這種方法會增加一個DLL。
要注意的是托管字符串和非托管字符串是有區別的,并需要轉換(特別要注意的Unicode字符串和多字節字符串的轉換)。
仍以MoveFile為例吧,這樣比較簡單:
#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文件,就可以直接調用了:
wrapper.ApiWrapper.MoveFile(@"c:\debug.log", @"c:\debug.txt");
假如原有的代碼是基于COM的,那么太好了,VisualStudio等IDE會自動生成一個用于包裝的dll,供你調用。當然因特殊需要而手工編碼的是另一回事。
場景三:現有C++原代碼,包裝后供C#調用。
C++的原代碼,實際上可以直接編譯成托管代碼。MFC也好ATL也好……這樣看起來在.NET中最強大的編程語言就是C++了:它不僅可以編寫托管程序,甚至可以將標準C++的代碼也編譯成托管程序!其實VC++最強大的地方不止如此,它還在于能夠編寫混合了托管和非托管的代碼的程序!!!這樣最大的好處不僅可以將關鍵代碼直接編譯成非托管的代碼,還可以避免被反編譯。
假設現有C++代碼如下:

class UnmanagedClass
{
public:

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

void MethodB( LPCWSTR )
{}
};
我們只要再增加一個包裝類到工程文件中:
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;
};
}
然后,改變編譯選項為“使用公共語言擴展 /clr”就可以了。這樣,我們把代碼編譯成DLL文件就可以供.NET其它語言調用了。
最后,C#中可以象如下的代碼一樣調用C++類了:
ManagedClass mc = new ManagedClass();
mc.MethoB("Hello");
string s = mc.get_PropertyA;
場景四:如何在托管C++代碼中混合托管和非托管代碼
很簡單,只要從#pragma unmanaged編譯指示開始的程序,一率編譯成非托管代碼;要想恢復成托管代碼,只要使用#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 函數:
[PreserveSig, MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType=MethodCodeType.Native), SuppressUnmanagedCodeSecurity]
public static unsafe void modopt(CallConvCdecl) f<char const *>(sbyte modopt(IsSignUnspecifiedByte) modopt(IsConst)*);
看不到源碼,而方法屬性標記為Unmanaged。
如果沒有加上#pragma unmanaged,反編譯得到的 f 函數為:
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);
}
其中的函數內容一目了然。如果你的函數沒有調用operator等不好理解的類庫,那么反編譯出來的代碼簡直和源碼沒差別。
開心一刻:我只會C++不懂.NET不懂C#,怎么編寫.NET程序?
很簡單,你照樣用你的C++寫你的程序,然后測試沒有錯誤后,將編譯選項改為/clr,好了,Rebuild,你的程序現在是.NET了。
惡搞:“我想問一下,在能將現有的C++代碼直接進行封裝,被C#進行調用,而不是去調用DLL,也就是不生成DLL,就在C#下能直接調用VC的工程源文件不?”
我想,提問的人是不是指,現有c++源碼,但不想費勁去轉換成C#源碼,但又想能與C#一起編譯。
于是我就給了一個極其變態的方法,不過,個人是不建議使用這種變態的方法啊。方法如下:
1 先將C++源碼,改用CLR編譯選項,編譯成.NET的Assembly(DLL文件)。
2 然后用reflector等反編譯軟件,反編譯成C#代碼,并導出(reflector有專門的導出插件)。
3 將導出的C#代碼,添加上新寫的C#代碼一起編譯。
這種方法生成的代碼很是恐怖,強烈建議不要把C++源碼就這么丟了,否則后果自負。