您的位置:首页 > 编程语言 > C语言/C++

C++调用C#编译的动态连接库

2014-03-07 23:57 513 查看
最近老板说要试下google的语音识别,于是上网找了一些代码,最多的一篇就是C# 调用Google语音识别。  下载过来运行,前面几天一直是服务器内部500错误。 以为代码问题,今天又试了一下,居然可以用了(不知道什么原因。。)。    由于需要在C++上用,偷懒的办法就是C++调用C#动态链接库,下面是过程:

1. 编译c#动态链接库

新建C#项目,选择“类库”。 代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace googleLib
{
public class SpeechRecognize
{

public bool GoogleSR(string inFileName,string format,int rate,ref string recResults)
{
recResults = "";
try
{
FileStream fs = new FileStream(inFileName, FileMode.Open);
byte[] voice = new byte[fs.Length];
fs.Read(voice, 0, voice.Length);
fs.Close();
HttpWebRequest request = null;
string url = "http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN";
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
//request.ContentType = "audio/x-flac; rate=16000";
request.ContentType = "audio/" + format + ";rate=" + rate.ToString();
request.ContentLength = voice.Length;
using (Stream writeStream = request.GetRequestStream())
{
writeStream.Write(voice, 0, voice.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
recResults = readStream.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
recResults = ex.ToString();
return false;
}
return true;
}

}
}


编译成dll。

(2) C++调用dll

  a. C++文件中添加dll

#using "googleLib.dll"
using namespace System;

  using namespace googleLib;

编译出现错误:

未处理的“System.IO.FileNotFoundException”类型的异常出现在 testgoogle.exe 中。

其他信息: 未能加载文件或程序集“googleLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。系统找不到指定的文件。

解决办法有两种:

  a. 在c++项目属性里面,选择“引用”,“添加新引用”



  b. 直接把dll拷贝到debug文件夹下

(3) C++王C#传递String

我在C++下调用函数  GoogleSR(string inFileName,string format,int rate,ref string recResults);

最后一个参数是string的引用,在C++中使用string,或者char 都会报错(原因没有深入研究)。

解决办法:

System::String^ strResults = gcnew System::String("");

speechRec->GoogleSR("","x-flac",16000,strResults);

这样就OK了

(4) C#的字符串String和C++的 Cstring相互转化

//CString convert to C# String

  CString s("JiangSu");

  String^ str1=gcnew String(s);

// C# String convert to CString 

        System::String^ strResults = gcnew System::String("");
CString results = CString( strResults ); 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: