"CString" (Compiled Type)
"CString"
represents a string compatible with C.
Constructors
- Unless wrapped with "Managed", C strings constructed with CreateTypeInstance are not automatically memory managed, and must be manually freed with DeleteObject. »
- CreateTypeInstance["CString",str] constructs a C string from a "String" str.
- CreateTypeInstance["CString",len] constructs a C string with length len.
- CreateTypeInstance["CString",cstr,len] constructs a copy of cstr with length len. If cstr is shorter than len, this can cause a crash.
- CreateTypeInstance["CString",cstr] constructs a copy of a null-terminated string cstr. If cstr is not null terminated, this can cause a crash.
Conversions
- Array types can be Cast to managed C strings. Supported array types include "ListVector", "NumericArray" and "PackedArray".
- Cast can be used to convert "String" objects to managed C strings.
- Cast can be used to bitcast C strings to and from raw pointers.
Arrays
"String"
"RawPointer" and "OpaqueRawPointer"
Examples
open all close allBasic Examples (1)
Compile a function that creates a managed C string and passes it to the C standard library function strlen to get its length:
cf = FunctionCompile[Function[Typed[str, "String"],
With[{cstr = CreateTypeInstance["Managed"::["CString"], str]},
LibraryFunction["strlen"][cstr]
]
]]Evaluate the compiled function on a string:
cf["Hello, World!"]Scope (2)
Compile a function that parses a C string to a number using the atof library function from the C standard:
cf = FunctionCompile@Function[{},
Module[{cstr},
cstr = TypeHint["3.14", "CString"];
LibraryFunction["atof"][cstr]
]
]Evaluate the compiled function:
cf[]Convert a "CInt" to a string and store it in a managed C string of size 512:
libDecl = LibraryFunctionDeclaration[
"snprintf",
{"CString", "CInt", "CString", "CInt"} -> "Integer32"
];
fun = Function[{Typed[n, "CInt"]},
Module[{size, cstr, fmt, err},
size = TypeHint[512, "CInt"];
cstr = CreateTypeInstance["Managed"::["CString"], size];
fmt = TypeHint["%d", "CString"];
err = LibraryFunction["snprintf"][cstr, size, fmt, n];CreateTypeInstance["String", cstr]
]
];
func = FunctionCompile[libDecl, fun]func[42]//InputFormPossible Issues (1)
C strings created outside of a "Managed" object are not automatically memory managed, and must be freed manually. Compile a function that creates unmanaged C strings:
cf1 = FunctionCompile[Function[{},
With[{carr = CreateTypeInstance["CString", 100]},
Null
]]]With[{before = MemoryInUse[]}, Do[cf1[], 10];MemoryInUse[] - before]Use DeleteObject to manually free the C strings:
cf2 = FunctionCompile[Function[{},
With[{carr = CreateTypeInstance["CString", 100]},
DeleteObject[carr]
]]]The resulting function does not leak memory:
With[{before = MemoryInUse[]}, Do[cf2[], 10];MemoryInUse[] - before]See Also
LibraryFunctionDeclaration DeleteObject
Compiled Types: String CArray CChar RawPointer OpaqueRawPointer
Tech Notes
Related Guides
History
Introduced in 2022 (13.1)