获取位置内存指针指向的字符串大小

时间:2012-05-15 23:13:59

标签: c++

我希望在本机C ++中获取由位置内存指针指向的字符串的字符:

对于C#中的等效实现,它将是:

int positionMemory = getPosition();

long size = 10;

string result = Marshal.PtrToStringAnsi(new IntPtr(positionMemory), size);

如何在C ++中生成结果?

2 个答案:

答案 0 :(得分:3)

我有一种感觉,这会导致问题......

以下内容应该或多或少等同于您提供的C#代码段,但结果字符串(存储在result中)仍然是“ANSI” - 它不会扩展到UNICODE,就像在C#片段。

int positionMemory = getPosition();
long size = 10;

std::string result( reinterpret_cast<const char *>(positionMemory), size);

请注意,size个字符将放在result中 - 包括'/0'个字符,因此如果您尝试将字符串传递给期望使用{{1}的C风格的字符串的字符串你可能会得到一些意想不到的结果。

此外,关于使用c_str()作为指针的常见警告(特别是如果您希望它有希望在64位系统上工作)也适用。

答案 1 :(得分:1)

假设“string”是由char表示的内存位置positionMemory s的一系列空终止,您可以通过strlen获取长度

const char* str = static_cast<const char*>(positionMemory);
int length = strlen(str);

但是,根据您创建字符串的演示代码判断,这可能是您想要的,并且是更好的代码:

std::string result = static_cast<const char*>(positionMemory);
int length = result.length();
相关问题