我一直在尝试使用 C++ 字符串类丰富方法(find_first_of、replace)来处理任务的某些字符串。
我围绕上述代码创建了一个包装文件,它可以包含在“C”源文件中并获得功能。
strUtils.h
#ifdef __cplusplus
extern "C" {
#endif
void doTheStringWork(char *inStr, unsigned beginLoc);
#ifdef __cplusplus
}
#endif
strUtils.cpp
#include "strUtils.h"
/*some standard includes here*/
void doTheStringWork(char *inStr, unsigned beginLoc) {
std::string inStr_s(inStr);
/* Doing some processing with the string object inStr_s*/
/* .......*/
/* Done */
return;
}
现在我遇到了一个问题,据我所知,如果不制作拷贝就无法解决。因此,我在此寻求您的帮助。
问题是我需要将 doTheStringWork
函数完成的更改返回到调用者的位置。您可能会说将 .c_str()
值作为 func 的返回值或以某种方式获取拷贝。这种方法效果很好,但对于我的任务来说,它变得非常慢,因为字符串可能太长,我可能需要它递归处理。
简而言之:我们能否围绕一个 char 指针创建一个字符串对象,我可以在其中使用所有字符串函数,而 char 指针反射(reflect)了所有这些变化。如果使用标准库无法实现这样的事情,有人可以提供一种方法,我怎样才能在这里实现我的目标。
最佳答案
最好的解决方案是放弃 C,使用 C++ 并摆脱困惑。但由于您可能无法做到这一点,下一个最佳解决方案是创建您自己的 C 可见结构和一些 C 可见函数(本质上是 PIMPL),在 C++ 源代码中定义它们(这样您就可以获得 std::string< 的好处
) 并从 C 中使用它们。像这样。
在 strUtils.h
header 中:
#ifdef __cplusplus
extern "C" {
#endif
typedef struct cpp_string cpp_string;
cpp_string *cpp_string_create(const char *txt, int size);
void cpp_string_free(cpp_string *);
cpp_string *cpp_string_add(cpp_string *, cpp_string *);
... // all operations you need
#ifdef __cplusplus
}
#endif
在 C++ 源代码中(strUtils.cpp
):
#include <string>
struct cpp_string {
std::string str;
cpp_string(std::string str): str(std::move(str)) { }
};
extern "C" cpp_string *cpp_string_create(const char *txt, int size)
{
return new cpp_string{ std::string{ txt, (size_t)size } };
}
// fill operations here
// since this is C++ file, just use std::string without copying
现在,当你想使用它时,你可以这样做:
int main()
{
cpp_string *s = cpp_string_create("qwerty", 6);
// do something with s
// dont forget to free s
cpp_string_free(s);
return 0;
}
这通过创建您自己的数据来回避整个 can-i-overwrite-someone-elses-memory(不,你不能,除非你想遇到奇怪的问题)。
关于c++ - 我们可以从 char 指针创建一个 C++ 字符串对象,其中对字符串对象的操作反射(reflect)到源 char 指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937054/