- Joined
- Jul 31, 2017
- Messages
- 500
Out of curiosity I tried to play around with cpp. I had this function ftime in BMax, that used standard c functions time, localtime and strftime to format the local time into a string - and after many tries now I got it running in Cerberus! Why? For fun, of course. And also to learn about the capabilities of CX
ftime.cxs
and ftime.cpp
ftime.cxs
Code:
' ftime.cxs
' compiles as STDCPP
Strict
Import "ftime.cpp"
Extern
Function malloc_:Int( size:Int ) ' allocate memory block
Function peekchar_:Int( mem:Int, pos:Int ) ' read char from memory block
Function time_:Void( time:Int ) ' get current system time
Function localtime_:Int( time:Int ) ' translate time to tm struct
Function strftime_:Void( buf:Int, size:Int, fmt$, time:Int ) ' format time into
' string in buf
Public
Function Main:Int()
Print( ftime("%A, %Y-%m-%d %H:%M:%S") )
Return 0
End
' returns current time in the format defined in pFString
Function ftime:String( pFString:String )
Local time:Int = malloc_(64) ' memory for time
Local timestring:Int = malloc_(256) ' buffer for string
time_(time) ' get current system time
Local tm:Int = localtime_(time) ' translate to tm struct
strftime_(timestring, 256, pFString, tm) ' format into string
' make int array from buffered chars
Local ret:Int[256]
For Local i:Int = 0 Until 256
ret[i] = peekchar_(timestring, i)
Next
' return string from int array
Return String.FromChars( ret )
End Function
and ftime.cpp
C++:
// wrapper function for: time_t time (time_t* timer);
// except it doesn't return anything
void time_( long long int ttime ){
time( (time_t*)ttime );
}
// wrapper function for: struct tm * localtime (const time_t * timer);
// returns the address of the tm structure as cerberus compatible int
int localtime_( long long int ttime ){
return (long long int)localtime( (time_t*)ttime );
}
// wrapper function for: size_t strftime (char* ptr, size_t maxsize,
// const char* format, const struct tm* timeptr );
int strftime_( long long int buf, int size, String fmt, long long int ttime ){
return strftime( (char*)buf,size,fmt.ToCString<char>(), (tm*)ttime );
}
// wrapper function for: void* malloc (size_t size);
// returns the address of the allocated block as a cerberus compatible int
int malloc_( int size ){
return (long long int)malloc( size );
}
// reads a char from a block at a defined position
// returns the char as a cerberus compatible int
int peekchar_( long long int mem, int pos ){
char* pmem = (char*)mem;
return (int)pmem[pos];
}
Last edited by a moderator: