tempCString

Creates temporary 0-terminated C string with copy of passed text.

tempCString
(
To = char
From
)
(
scope From str
)
if (
isSomeChar!To &&
(
isInputRange!From ||
isSomeString!From
)
&&
isSomeChar!(ElementEncodingType!From)
)

Parameters

To

character type of returned C string

str From

string or input range to be converted

Return Value

Type: auto

The value returned is implicitly convertible to const To* and has two properties: ptr to access C string as const To* and buffPtr to access it as To*.

The value returned can be indexed by [] to access it as an array.

The temporary C string is valid unless returned object is destroyed. Thus if returned object is assigned to a variable the temporary is valid unless the variable goes out of scope. If returned object isn't assigned to a variable it will be destroyed at the end of creating primary expression.

Implementation note

For small strings tempCString will use stack allocated buffer, for large strings (approximately 250 characters and more) it will allocate temporary one using C's malloc.

Note: This function is intended to be used in function call expression (like strlen(str.tempCString())). Incorrect usage of this function may lead to memory corruption. See WARNING in Examples section.

Examples

import core.stdc.string;

string str = "abc";

// Intended usage
assert(strlen(str.tempCString()) == 3);

// Correct usage
auto tmp = str.tempCString();
assert(strlen(tmp) == 3); // or `tmp.ptr`, or `tmp.buffPtr`

// $(RED WARNING): $(RED Incorrect usage)
auto pInvalid1 = str.tempCString().ptr;
const char* pInvalid2 = str.tempCString();
// Both pointers refer to invalid memory here as
// returned values aren't assigned to a variable and
// both primary expressions are ended.

Meta