• <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++ 基礎} {C++ 高級} {C#界面,C++核心算法} {設計模式} {C#基礎}

            CLI中native的string和System::String轉化


            一 實例 (代碼下載 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++源碼就這么丟了,否則后果自負。


             

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

            評論

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

            呵呵,這個當年我也整過,不過是項目經理搞定的  回復  更多評論   

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

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

            至于他們的互相轉換我是這樣做的:
            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;
            }  回復  更多評論   

            # re: CLI中native的string和System::String轉化 2008-07-17 14:33 夢在天涯

            // 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;
            }  回復  更多評論   

            # re: CLI中native的string和System::String轉化 2008-07-17 14:34 夢在天涯

            // 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);
            }  回復  更多評論   

            公告

            EMail:itech001#126.com

            導航

            統計

            • 隨筆 - 461
            • 文章 - 4
            • 評論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804154
            • 排名 - 5

            最新評論

            閱讀排行榜

            996久久国产精品线观看| 99久久婷婷国产综合亚洲| 久久久久久久亚洲Av无码| 精品久久久久成人码免费动漫| 99久久免费国产精精品| 午夜精品久久久久久久| 久久久久99这里有精品10 | 久久精品国产第一区二区三区| 久久成人精品| 久久婷婷五月综合色奶水99啪| 成人久久免费网站| 99久久精品免费| 97视频久久久| 国内精品久久久久久久coent| 久久夜色精品国产噜噜亚洲a| 狠狠色综合网站久久久久久久高清 | 久久精品人妻一区二区三区| 久久99国产乱子伦精品免费| 日产精品久久久一区二区| 精品无码久久久久久尤物| 久久国产V一级毛多内射| 久久久久久精品免费免费自慰| 国产精品一区二区久久国产| 久久天天躁狠狠躁夜夜avapp| 色综合久久久久| 久久精品国产第一区二区三区 | 国产精品久久久久影院色| 久久精品国产欧美日韩| 久久综合视频网| 久久毛片免费看一区二区三区| 久久99久久99小草精品免视看| 色婷婷综合久久久久中文字幕 | 99久久精品午夜一区二区| 99久久精品国产综合一区| 亚洲香蕉网久久综合影视| 成人资源影音先锋久久资源网| 色综合久久无码中文字幕| 国内精品久久久久影院免费| 久久综合九色综合久99| 久久精品国产亚洲av高清漫画| 伊人久久大香线焦AV综合影院|