"CArray" (Compiled Type)
[Experimental]
"CArray"::[type]
represents an array type compatible with C, containing elements of the specified type.
Details
- "CArray" can be used in Typed and related constructs to specify a type.
- Objects with type "CArray" are not automatically memory managed and must be manually freed.
- "CArray"::[t] is equivalent to t* in C.
- "CArray" can be used when interfacing with external libraries that are compatible with C.
- Internally, objects with type "CArray" are represented with pointers.
Constructors
- Unless wrapped with "Managed", C arrays constructed with CreateTypeInstance are not automatically memory managed, and must be manually freed with DeleteObject. »
- CreateTypeInstance["CArray"::[type],len] constructs a C array with length len.
- CreateTypeInstance["CArray"::[type],carr,len] constructs a copy of the C array carr with length len.
- CreateTypeInstance["CArray"::[type],array] constructs a C array containing elements of the given array. Supported array types include "ListVector", "NumericArray" and "PackedArray".
- CreateTypeInstance["Managed"::["CArray"::[type]],…] constructs a memory-managed C array.
Properties
- Information[carr,"ElementType"] for carr of type "CArray"::[type] gives type .
- FromRawPointer[carr,offset] indexes the C array carr. Indexes start with 0.
Conversions
- Array types can be Cast to managed C arrays. Supported array types include "ListVector", "NumericArray" and "PackedArray".
- Cast can be used to bitcast C arrays to and from raw pointers.
Arrays
"RawPointer" and "OpaqueRawPointer"
Examples
open allclose allBasic Examples (2)Summary of the most common use cases
Create a memory-managed C array, and then access one of its elements:
In[1]:=1

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-5p6ne4
Out[1]=1

In[2]:=2

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-q6h2wb
Out[2]=2

Represent a function from an external library that takes a C array as an argument:
In[1]:=1

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-b111du
Compile a program that creates a C array and calls the function:
In[2]:=2

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-87nx61
Out[2]=2

In[3]:=3

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-8oqtaf
Out[3]=3

Possible Issues (1)Common pitfalls and unexpected behavior
C arrays created outside of a "Managed" object are not automatically memory managed, and must be freed manually. Compile a function that creates unmanaged C arrays:
In[1]:=1

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-1mgnnm
Out[1]=1

In[2]:=2

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-nqs4i4
Out[2]=2

Use DeleteObject to manually free the C arrays:
In[3]:=3

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-cymrrx
Out[3]=3

The resulting function does not leak memory:
In[4]:=4

✖
https://wolfram.com/xid/0s799o7k14pks2srnhezxg0w4e-9ewoj9
Out[4]=4
