其他分享
首页 > 其他分享> > c – 将_TCHAR *转换为char *

c – 将_TCHAR *转换为char *

作者:互联网

我试图让WindowsWindows上运行a simple OpenCV sample,而我的C不仅仅是生锈了.

The sample很简单:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    if( argc != 2)
    {
        cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
        return -1;
    }
    Mat image;
    image = imread(argv[1], IMREAD_COLOR); // Read the file
    if(! image.data )                      // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }
    namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.
    imshow( "Display window", image );                // Show our image inside it.
    waitKey(0); // Wait for a keystroke in the window
    return 0;
}

当我在Visual Studio 2012中创建一个新的简单C控制台应用程序(使用ATL)时,我得到一个不同的main模板:

int _tmain( int argc, _TCHAR* argv[] )

所以在我将文件名发送到OpenCV的imread函数之前,我需要将_TCHAR * arg [1]转换为char *.使用一个简单的文件名’opencv-logo.jpg’,从内存窗口的内存中我可以看到_TCHAR每个占用两个字节

o.p.e.n.c.v.-.l.o.g.o...j.p.g...
6f 00 70 00 65 00 6e 00 63 00 76 00 2d 00 6c 00 6f 00 67 00 6f 00 2e 00 6a 00 70 00 67 00 00 00

按照another answer中的转换建议,我尝试通过插入以下代码来使用ATL 7.0 String Conversion Classes and Macros

char* filename = CT2A(argv[1]);

但由此产生的内存是一团糟,当然不是’opencv-logo.jpg’作为ascii字符串:

fe fe fe fe fe fe fe fe fe fe ...
þþþþþþþþþþ ...

我应该使用哪种转换技术,功能或宏?

(N.B. This可能是一个相关的问题,但我看不到如何在这里申请the answer.)

解决方法:

最快的解决方案是将签名更改为标准签名.更换:

int _tmain( int argc, _TCHAR* argv[] )

int main( int argc, char *argv[] )

这在Windows上意味着命令行参数转换为系统的语言环境编码,并且由于Windows不支持UTF-8,因此并非所有内容都能正确转换.但是,除非你真的需要国际化,否则你可能不值得花时间去做更多的事情.

标签:tchar,atl,c,string,visual-c
来源: https://codeday.me/bug/20191008/1870989.html