背景:我要把一个非托管的vc库用vc.net包装以供C#中调用。
非托管dll中类:
- C/C++ code
class LANE_SPEECH_DLL CSR {public: void GetRecoWordA ( char * pchRecoWord ); void GetRecoWordW ( wchar_t * pwchRecoWord ); bool StartReco(); CSR(); bool Create( const DWORD dwLanguage = SP_CHINESE, const bool bInproc = true ); bool LoadCrammarFile ( const WCHAR * pwchFilename ); bool SetInputFromWav ( const WCHAR * pwchFileName, const SPSTREAMFORMAT FileFormat ); void ProcessReco( const DWORD dwMilliseconds = 5000 ); bool IsRecoSuccess() const; bool IsRecoEnd() const; virtual ~CSR();}
其中LANE_SPEECH_DLL 的定义为:
- C/C++ code
#ifdef USE_SPEECH_DLL #ifdef LANE_SPEECH_EXPORTS #define LANE_SPEECH_DLL __declspec(dllexport) #else #define LANE_SPEECH_DLL __declspec(dllimport) #endif#else #define LANE_SPEECH_DLL
包装类:
头文件中:
- C/C++ code
public ref class ManagedCSR { public: ManagedCSR(); String^ GetRecoWord(); bool StartReco(); bool Create(int language ,bool bInproc); bool Create(); bool SetInputFromWav(String^ fileName,const SPSTREAMFORMAT FileFormat); bool LoadGrammarFile(String^ fileName); void ProcessReco(int dwMilliseconds); bool IsRecoSuccess(); bool IsRecoEnd(); ~ManagedCSR(); const static int SP_CHINESE = 0x0000; //简体中文. const static int SP_ENGLISH = 0x0001; //英语. private: CSR* csr; };
cpp中:
- C/C++ code
ManagedCSR::ManagedCSR():csr(new CSR()) { } String^ ManagedCSR::GetRecoWord() { wchar_t *recWord = new wchar_t; csr->GetRecoWordW(recWord); String^ word = Marshal::PtrToStringUni(static_cast<IntPtr>(recWord)); delete [] recWord; recWord = NULL; return word; } bool ManagedCSR::StartReco() { return csr->StartReco(); } bool ManagedCSR::Create(const int language,bool bInproc) { return csr->Create(language,bInproc); } bool ManagedCSR::Create() { return csr->Create(ManagedCSR::SP_CHINESE,true); } bool ManagedCSR::SetInputFromWav(String^ fileName, const SPSTREAMFORMAT FileFormat) { IntPtr pString = Marshal::StringToHGlobalUni(fileName); try { wchar_t* wcFileName = static_cast<wchar_t *>(pString.ToPointer()); return csr->SetInputFromWav(wcFileName,FileFormat); } finally { Marshal::FreeHGlobal(pString); } } bool ManagedCSR::LoadGrammarFile(String^ fileName) { IntPtr pString = Marshal::StringToHGlobalUni(fileName); try { wchar_t* wcFileName = static_cast<wchar_t *>(pString.ToPointer()); return csr->LoadCrammarFile(wcFileName); } finally { Marshal::FreeHGlobal(pString); } } void ManagedCSR::ProcessReco( const int dwMilliseconds) { csr->ProcessReco(dwMilliseconds); } bool ManagedCSR::IsRecoSuccess() { return csr->IsRecoSuccess(); } bool ManagedCSR::IsRecoEnd() { return csr->IsRecoEnd(); } ManagedCSR::~ManagedCSR() { delete csr; }