Boolean type

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
stylin
Posts: 1253
Joined: Nov 06, 2005 5:19

Boolean type

Post by stylin »

Since boolean expressions in FreeBASIC have different values as those in C++, here's a TYPE that allows automatic conversion between the two when doing working with C++ code, make note of the name-mangling issue..

Code: Select all

// cpp.cpp - compile with 'g++ cpp.cpp'
//
extern void trueexpr ();
extern void falseexpr ();

extern "C" {
void a (bool expr) { expr == true ? trueexpr() : falseexpr(); }
}
extern
void b (bool expr) { expr == true ? trueexpr() : falseexpr(); }

Code: Select all

'' cppbool.bas - build with 'fbc cppbool.bas cpp.o'
''
type CPPBool
	' Creates a C++ bool from an integer expr (FB bool)
	declare constructor (as integer)
	' Converts a C++ bool to an integer expr (FB bool)
	declare function fb_bool as integer

	value as byte
end type

constructor CPPBool (expr as integer)
	this.value = iif(0 <> expr, 1, 0)
end constructor

function CPPBool.fb_bool as integer
	return this.value <> 0
end function

' no built-in name-mangling support for bool, so external C++ functions
' must be declared 'extern "C"' in C++ code, or given an alias in FB code
' with the mangled name.
extern "C"
declare sub a (byval as CPPBool)
end extern
declare sub b cdecl alias "_Z1bb" (byval as CPPBool)

extern "C++"
	' the above function calls one of the procedures below..
	sub trueexpr : print "true" : end sub
	sub falseexpr : print "false" : end sub
end extern

' call the C++ function, automatically converting FB's bool values to
' C++ bool values..
a(0 = 1)
a(1 = 1)
b(0 = 1)
b(1 = 1)
edit: updated code to conform to new BYREF default.
Post Reply