在库API中传递std :: string [英] Passing std::string in a library API

查看:146
本文介绍了在库API中传递std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在为某个图书馆建立API。
接口的一部分需要库来获取和返回用户类,例如向量和字符串。



当试图模拟在库中使用库简单的场景,在调试模式下,系统在传递一个字符串作为输入时会崩溃。



我相信在调试或发布模式下,字符串类有一个不同的表示。然后我们的库假设接收一个特定的表示,读取数据成员不正确,沿途粉碎。
那么,什么是在API中传输STL对象的最佳方法。
目标操作系统是使用MSVC 8编译的Windows XP,虽然库用户将使用窗口他们的编译器可能(可能会)不同
到目前为止的想法:


  1. 将字符串更改为char * - 但是开发人员可能会对释放内存的责任感到困惑。

  2. 使用我们自己的版本String - 我不想开发另一个私有的字符串实现。

  3. 发布到用户调试版本和发布版本。



解决方案 div>

你应该避免在不同的二进制模块之间传递STL对象。



对于字符串,你必须依赖 const char * code>只读参数和 char *,< buffer size> 用于输入参数...



对于向量,它可能有点更困难,尤其是如果你必须更改向量的内容...



关于你的想法:


  1. 你是对的,但是惯例通常是你不能存储传递的指针(你必须做你的本地副本)。

  2. 最后,除非在调试和发布版本的实现中使用相同的二进制表示,否则会有同样的问题。

  3. 如果使用不同的版本/在两个二进制模块中的STL实现(除非你确定库用户将使用相同的STL)。


We are currently building an API for a certain library. Part of the interface requires the library to get and return to the user classes such as vector and string.

When trying to simulate use of the library in a simple scenario, in debug mode the system crush when delivering a string as an input.

I believe there is a different representation of the string class in debug or release mode. Then our library assumes to receive a certain representation, read a data member incorrectly and crush along the way. So what is the best way method to transferring STL objects in an API. The target OS is windows XP compiled with MSVC 8, although the library user will use windows their compiler might (and probably will) be different Ideas we had so far:

  1. Change string to char* - But then developers might be baffled with the responsibility of releasing the memory.
  2. Use our own version of String – I don't want to develop another private implementation of string.
  3. Release to the user debug version and release version.
  4. Ask people on Stack overflow for some option we miss or don’t understand, or just hear from their experience - done.

解决方案

You should avoid passing STL objects between different binary modules.

For string, you have to rely on const char* for read only parameter and char*, <buffer size> for input parameters...

For vectors, it could be a bit more difficult especially if you have to change the content of the vector...

About your ideas:

  1. You are right, but the convention usually is that you can't store the passed pointer (you have to do your local copy).
  2. At the end you would have the same issue unless you have the same binary representation on debug and release version of your implementation.
  3. This may be harmful if you use different versions/implementation of STL in the two binary modules (unless you are sure that the library user will use the same STL).

这篇关于在库API中传递std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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