• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            C++ Programmer's Cookbook

            {C++ 基礎(chǔ)} {C++ 高級(jí)} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            CLI中native的string和System::String轉(zhuǎn)化


            一 實(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編譯指示開始的程序,一率編譯成非托管代碼;要想恢復(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)差別。 

              開心一刻:我只會(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文件)。
              2 然后用reflector等反編譯軟件,反編譯成C#代碼,并導(dǎo)出(reflector有專門的導(dǎo)出插件)。
              3 將導(dǎo)出的C#代碼,添加上新寫的C#代碼一起編譯。
              
              這種方法生成的代碼很是恐怖,強(qiáng)烈建議不要把C++源碼就這么丟了,否則后果自負(fù)。


             

            posted on 2008-03-12 16:47 夢(mèng)在天涯 閱讀(8417) 評(píng)論(4)  編輯 收藏 引用 所屬分類: Manage c++ /CLI

            評(píng)論

            # re: CLI中native的string和System::String轉(zhuǎn)化 2008-03-20 00:28 七星重劍

            呵呵,這個(gè)當(dāng)年我也整過(guò),不過(guò)是項(xiàng)目經(jīng)理搞定的  回復(fù)  更多評(píng)論   

            # re: CLI中native的string和System::String轉(zhuǎn)化 2008-05-04 11:26 陳梓瀚(vczh)

            無(wú)論如何還是要建立一個(gè)c++/cli工程,然后原來(lái)的部分使用#pragma unmanaged編譯,然后再用c++/cli加一個(gè)殼。c#的工程引用這個(gè)工程就行了。不過(guò)還是做成dll好。

            至于他們的互相轉(zhuǎn)換我是這樣做的:
            System::String^ ConvertString(const freescript::FsString& Source)
            {
            return gcnew System::String(Source.w_str());
            }

            freescript::FsString ConvertString(System::String^ Source)
            {
            System::IntPtr Pointer=System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni(Source);
            wchar_t* Buffer=(wchar_t*)(void*)(Pointer);
            freescript::FsString Result=Buffer;
            System::Runtime::InteropServices::Marshal::FreeCoTaskMem(Pointer);
            return Result;
            }  回復(fù)  更多評(píng)論   

            # re: CLI中native的string和System::String轉(zhuǎn)化 2008-07-17 14:33 夢(mèng)在天涯

            // convert_system_string.cpp
            // compile with: /clr
            #include <string>
            #include <iostream>
            using namespace std;
            using namespace System;

            void MarshalString ( String ^ s, string& os ) {
            using namespace Runtime::InteropServices;
            const char* chars =
            (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
            os = chars;
            Marshal::FreeHGlobal(IntPtr((void*)chars));
            }

            void MarshalString ( String ^ s, wstring& os ) {
            using namespace Runtime::InteropServices;
            const wchar_t* chars =
            (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
            os = chars;
            Marshal::FreeHGlobal(IntPtr((void*)chars));
            }

            int main() {
            string a = "test";
            wstring b = L"test2";
            String ^ c = gcnew String("abcd");

            cout << a << endl;
            MarshalString(c, a);
            c = "efgh";
            MarshalString(c, b);
            cout << a << endl;
            wcout << b << endl;
            }  回復(fù)  更多評(píng)論   

            # re: CLI中native的string和System::String轉(zhuǎn)化 2008-07-17 14:34 夢(mèng)在天涯

            // convert_string_to_wchar.cpp
            // compile with: /clr
            #include < stdio.h >
            #include < stdlib.h >
            #include < vcclr.h >

            using namespace System;

            int main() {
            String ^str = "Hello";

            // Pin memory so GC can't move it while native function is called
            pin_ptr<const wchar_t> wch = PtrToStringChars(str);
            printf_s("%S\n", wch);

            // Conversion to char* :
            // Can just convert wchar_t* to char* using one of the
            // conversion functions such as:
            // WideCharToMultiByte()
            // wcstombs_s()
            // ... etc
            size_t convertedChars = 0;
            size_t sizeInBytes = ((str->Length + 1) * 2);
            errno_t err = 0;
            char *ch = (char *)malloc(sizeInBytes);

            err = wcstombs_s(&convertedChars,
            ch, sizeInBytes,
            wch, sizeInBytes);
            if (err != 0)
            printf_s("wcstombs_s failed!\n");

            printf_s("%s\n", ch);
            }  回復(fù)  更多評(píng)論   

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評(píng)論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804173
            • 排名 - 5

            最新評(píng)論

            閱讀排行榜

            久久成人18免费网站| 无码AV中文字幕久久专区| 91久久精品国产免费直播| 久久综合丁香激情久久| 久久久久亚洲精品男人的天堂| 热久久国产欧美一区二区精品| 久久精品卫校国产小美女| 精品久久久久久综合日本| 无码任你躁久久久久久| 97热久久免费频精品99| 久久综合伊人77777| 国产精品久久国产精品99盘| 久久se这里只有精品| 久久精品国产亚洲77777| 久久久久亚洲精品无码网址| 高清免费久久午夜精品| 久久婷婷色香五月综合激情| 欧美精品一区二区精品久久 | 国产精品久久久久久一区二区三区| a高清免费毛片久久| 亚洲AV无码一区东京热久久| 久久精品国产精品亚洲| 久久最近最新中文字幕大全| 久久久久久亚洲Av无码精品专口| 四虎久久影院| 欧美麻豆久久久久久中文| 国产精品伊人久久伊人电影 | 久久午夜福利电影| 狠狠干狠狠久久| 精品久久8x国产免费观看| 亚洲精品乱码久久久久久按摩 | 国产产无码乱码精品久久鸭| 国产69精品久久久久观看软件 | 久久青青草原精品国产| 国产成人精品综合久久久久| 国产69精品久久久久观看软件| 久久久久99精品成人片三人毛片| 国产午夜精品理论片久久| 精品久久久久久国产牛牛app| segui久久国产精品| 欧美久久一区二区三区|