On Saturday, 27 April 2013 at 23:38:17 UTC, bearophile wrote:
Jeremy DeHaan:
I was reading this:
http://dlang.org/cpp_interface.html
And it mentions the various types and their compatibility with
one another, but it leaves out bools. It would be very useful
for me if it works out like this, but does anyone know off the
top of their heads/tried it before?
If it misses bool, then maybe that page needs a documentation
patch.
bools in D are represented with 1 byte, 0 or 1.
In C++ their size is not fixed: "for Visual C++ 4.2, a call of
sizeof(bool) yields 4, while in Visual C++ 5.0 and later, the
same call yields 1."
Bye,
bearophile
Well I realized that I was being dumb in the sense that I am
mainly using a C interface and not really a C++ interface. That
said, after playing with some ideas, I have something that works,
though I am not entirely sure how safe it is.
Consider the following,
In C/C++....
DBoolTest.h:
typedef char DBool;
#define DTrue 1;
#define DFalse 0;
SOME_EXPORT_MACRO DBool isAGreaterThanB(int a, int b);//this is
an extern "C" dll export macro
DBoolTest.cpp:
#include "DBoolTest.h"
DBool isAGreaterThanB(int a, int b)
{
if(a>b)
{
return DTrue;
}
else
{
return DFalse;
}
}
In D...
main.d:
module main;
import std.stdio;
void main(string[] args)
{
writeln("Is 1 greater than 2?");
writeln(isAGreaterThanB(1,2));
// Lets the user press <Return> before program returns
stdin.readln();
}
extern(C)
{
bool isAGreaterThanB(int a, int b);
}
Linking the D program with the C/C++ DLL and running main.exe
results in the output:
Is 1 greater than 2?
false
D bools are 1 byte, and C/C++ chars are 1 byte as well and it
works. How safe is it to mix types like this between the two
languages though? I would rather have a nice clean solution than
to put together something that is considered "hacky." That said,
if something like this isn't a big deal, it would make my D code
more straight forward and a little cleaner.
Any thoughts on this guys?
Jeremy