C++ c_str of std::string 返回空 [英] C++ c_str of std::string returns empty
问题描述
所以,我遇到了以下代码的问题,其中 std::cout <<cstr<
So, I'm running into an issue with the following code whereby the result of std::cout << cstr << std::endl
is the single character
PyObject * CKKSwrapper::SerializeContext() {
std::string s; // 1
std::ostringstream os(s); // 2
Serial::Serialize(m_cc, os, SerType::BINARY); // 3
const std::string string_repr = os.str(); // 4
std::cout << string_repr << std::endl; // 5
char *cstr = new char[string_repr.length() + 1]; // 6
std::strcpy(cstr, string_repr.c_str()); // 7
std::cout << "******************************************************" << std::endl; // 8
std::cout << string_repr << std::endl; // 9
std::cout << "******************************************************" << std::endl; // 10
std::cout << cstr << std::endl; // 11
auto resp = PyBytes_FromString(cstr); // 12
return resp;
}
检查第 5 行的 std::cout
结果看起来不错并且是非空的.
Checking the std::cout
result on line 5 looks good and is non-empty.
@ 4 lbcrypto::LPCryptoParametersCKKSlbcrypto::DCRTPoly @
@ � �4 lbcrypto::LPCryptoParametersCKKSlbcrypto::DCRTPoly � @ �
^ 前几个字符(不确定是否有帮助)
^ the first few characters (not sure if that helps)
稍后,我创建了一个字符数组并将 c_str
复制到它,这(我认为)避免了讨论的临时结果问题 https://stackoverflow.com/a/39006531/3532564
Later, I create a char array and copy over the c_str
to it which (I think) avoids the issue of a temporary result as was discussed https://stackoverflow.com/a/39006531/3532564
不要试图存储 c_str() 返回的指针.如果您需要将该字符串作为 C 字符串长时间使用,请自行为其分配内存缓冲区并将 c_str() 的结果复制到该缓冲区.
Don't attempt to store the pointer returned by c_str(). If you need that string as a C-string for an extended period of time, allocate memory buffer for it yourself and copy the result of c_str() to that buffer.
我还发现了 https://stackoverflow.com/a/35981001/3532564 这让我想知道我的 string_repr
对象被销毁了,所以我在第 9 行做了一个 std::cout,它看起来也不错.
I also found https://stackoverflow.com/a/35981001/3532564 which made me wonder if my string_repr
object was being destroyed so I did a std::cout on line 9 and it looks good also.
谁能帮帮我?我真的不确定问题出在哪里.不幸的是,我需要将 char * []
传递给 PyBytes_FromString
,尽管名称可能让人想到
Can anyone help me? I'm really not sure where the issue stems from. Unfortunately, I need to pass a char * []
to PyBytes_FromString
despite what the name might make one think
推荐答案
大概字符串包含一个或多个 nul
字符,导致 strcpy()
没有复制所有字节.在从函数返回之前不释放 cstr
也会导致内存泄漏.
Presumably the string contains one or more nul
characters, resulting in strcpy()
not copying all of the bytes. You also have a memory leak from not freeing cstr
before you return from the function.
您可以通过绕过不必要的字符串数组并调用 PyBytes_FromStringAndSize
来避免这两个问题:
You can avoid both problems by bypassing the unnecessary string array and calling PyBytes_FromStringAndSize
:
return PyBytes_FromStringAndSize(string_repr.c_str(), string_repr.size());
这篇关于C++ c_str of std::string 返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!