Use another language to call a function: Difference between revisions

Add an easy C++ answer.
m (→‎Using cptr and memcpy: Nuke trailing spaces.)
(Add an easy C++ answer.)
Line 149:
$
</lang>
 
=={{header|C++}}==
<lang cpp>#include <string>
using std::string;
 
// C++ functions with extern "C" can get called from C.
extern "C" int
Query (char *Data, size_t *Length)
{
const string Message = "Here am I";
 
// Check that Message fits in Data.
if (*Length < Message.length())
return false; // C++ converts bool to int.
 
*Length = Message.length();
Message.copy(Data, *Length);
return true;
}</lang>
 
We must compile main() with a C compiler and Query() with a C++ compiler. One can use gcc and g++ (or clang and clang++).
 
<lang bash>$ gcc -c main.c
$ g++ -c query.cpp
$ g++ -o main main.o query.o
$ ./main
Here am I</lang>
 
=={{header|D}}==
Anonymous user