简体   繁体   中英

C++ how would I cast a string to a pointer?

I'm playing with this C wrapper for the OpenCV function imread.

 Mat* cv_imread(String* filename, int flags) {
     return new Mat(cv::imread(*filename, flags));
 }

It's failing somewhere I think so I'm trying to test to make sure it's written right. I just need to know how to create a String* to fill its first argument.. I've tried creating a string with

 char* filename = "~/home/test.jpg"

then casting to String* i/e

 (String*)filename

but that's not working..I've tried many other variations to cast to pointer found online but found nothing cv_imread would accept. In my code it's necessary to have the filename parameter be a String* and not another type. But I could use help creating a String* to give to cv_imread .

Edit: per your edit I tried

 const char* filename = "/home/w/d1";


 cv_imread(new string (filename), 1);

but got error:

cannot convert 'std::string* {aka std::basic_string }' to 'cv::String ' for argument '1' to 'cv::Mat* cv_imread(cv::String*, int)' cv_imread(new string (filename), 1);

If you can help me with it I'd appreciate it

Use string::c_str() to get the underlying pointer of a string:

Mat* cv_imread(String* filename, int flags) {
     return new Mat(cv::imread(filename->c_str(), flags));
}

Or you can use string::data() too. They have the same functionality after C++11.


Edit: OP seems to want to pass a char* to cv_read . Then should do this:

cv_read(new String(filename), 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM