将 STL 字符串从 C++/CLI 应用程序传递给 C++ DLL [英] Passing an STL string to a C++ DLL from a C++/CLI app

查看:65
本文介绍了将 STL 字符串从 C++/CLI 应用程序传递给 C++ DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 OpenCV 的 C++/CLI 项目.我自己在 VS 2010 中编译了这个版本的 OpenCV,我可以在非托管项目中使用它而不会出现问题——当我尝试在托管项目中使用它时,麻烦就开始了.

I have a C++/CLI project using OpenCV. I compiled this version of OpenCV in VS 2010 myself and I can use it in unmanaged projects without an issue — the trouble started when I tried to use it in a managed one.

感兴趣的函数是cv::imread(std::string&, int).简单地从托管模块调用它根本不起作用,产生<无效指针>在接收端.我有点期待它.毕竟,托管代码有自己的 std::string 实现.

The function of interest is cv::imread(std::string&, int). Simply calling it from a managed module did not work at all, producing <invalid pointer> on the receiving end. I was sort of expecting it. After all, managed code has its own std::string implementation.

当我创建一个单独的 C++ 文件、从其模块中删除 CLI 支持并将我的代码放入其中时,事情变得更有趣了.现在,imread 得到了一个有效的指针,但它的内容被打乱了.显然,我传递给它的 string 包含偏移 4 个字节的字符串指针,但它希望它位于 0 偏移处.

Things got a little more interesting when I created a separate C++ file, removed CLI support from its module, and placed my code in it. Now, imread was getting a valid pointer, but its contents were scrambled. Apparently, the string I was passing it contained the string pointer offset by 4 bytes, but it expected it to be at the 0 offset.

非托管模块使用与 OpenCV 相同的 CRT DLL,并将所有选项设置为适合正常 OpenCV 使用的值.为什么它会有不同的 string 布局?我迷路了.

The unmanaged module is using the same CRT DLL as OpenCV and has all options set to the values appropriate for normal OpenCV use. Why would it have a different string layout? I am lost.

示例代码:

#include <opencv/cv.h>
#include <opencv/highgui.h>

#include <string>

using namespace cv;
using namespace std;

void Run()
{
    string path("C:\\Users\\Don Reba\\Pictures\\Merlin 1D.jpg");

    Mat image(imread(path, CV_LOAD_IMAGE_GRAYSCALE));
    imwrite("image.jpg", image);
}

推荐答案

问题是 Visual Studio 2010 默认为 C++ 和 C++/CLI 项目使用不同的工具集.这就是为什么 STL 类尽管设置相同但具有不同布局的原因.要解决此问题,请确保在 C++/CLI 项目中将 Configuration Properties/General/Platform Toolset 设置为 v100.

The problem is that Visual Studio 2010 uses different toolsets for C++ and C++/CLI projects by default. This is why STL classes have different layouts despite identical settings. To fix the problem, make sure that Configuration Properties / General / Platform Toolset is set to v100 in the C++/CLI project.

这篇关于将 STL 字符串从 C++/CLI 应用程序传递给 C++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆