Click or drag to resize

MemCAlloc Function

X#
Allocate static memory buffers of a specified size.

Namespace:  XSharp.RT
Assembly:  XSharp.RT (in XSharp.RT.dll) Version: 2.19
Syntax
 FUNCTION MemCAlloc(
	wItems AS DWORD,
	wBytes AS DWORD
) AS IntPtr
Request Example View Source

Parameters

wItems
Type: DWord
The number of items to allocate memory for.
wBytes
Type: DWord
The number of bytes to allocate for each item.

Return Value

Type: IntPtr
A pointer to the allocated space if there is sufficient memory available; otherwise, a NULL_PTR. You should always check the return value from MemCAlloc() for a successful allocation.
Remarks
MemCAlloc() is useful in allocating space for several items at one time.
The allocated memory is defined to be static so that it is not moved by the garbage collector. Space allocated by MemCAlloc() is freed by MemFree().
Tip Tip
This function allows the direct manipulation of a memory location and should be used with extreme care.
Remarks
Tip Tip
The Static Memory Functions (MemAlloc, MemSet etc) are included for compatibility only. In most cases the static memory blocks can (and should) be replaced with arrays of bytes.
Many of the functions in the runtime that take memory blocks as parameter, such as the low level IO functions, now have overloads that take arrays of bytes as parameter.
We recommend that you use these overloads, because their performance is somewhat better.
Examples
This example uses MemCAlloc() to allocate space for ten long integers:
X#
1LOCAL ptrLongs AS PTR
2ptrLongs := MemCAlloc(10, 4)
Instead of hard-coding 4 for the size of a long integer, we could have issued:
X#
1ptrLongs := MemCAlloc(10, _SizeOf(LONG))
This next example uses MemCAlloc() to allocate space for five instances of a defined structure:
X#
 1STRUCTURE StatInfo
 2    MEMBER wAverageHit AS DWORD
 3    MEMBER wMaxHit AS DWORD
 4    MEMBER wMinHit AS DWORD
 5FUNCTION MemCAlloc2() AS VOID
 6    LOCAL ptrStruct AS PTR
 7    ptrStruct := MemCAlloc(5, _SizeOf(StatInfo))
 8    IF ptrStruct = NULL_PTR
 9        ? "Allocation failed"
10    ELSE
11        MemFree(ptrStruct)
12    ENDIF
See Also