You are on page 1of 4

ExampleCxx

July 19, 2018

1 Using C++ with Julia


In [2]: using Cxx

1.1 Embedding a simple C++ function in Julia


In [2]: cxx"#include <iostream>"

Out[2]: true

In [3]: cxx"""
void mycppfunction() {
int z = 0;
int y = 5;
int x = 10;
z = x * y + 2;
std::cout << "The number is " << z << std::endl;
}
"""

Out[3]: true

In [4]: julia_function() = @cxx mycppfunction()

Out[4]: julia_function (generic function with 1 method)

In [5]: julia_function()

The number is 52

1.2 Passing numeric arguments from Julia to C++


In [6]: jnum = 10

Out[6]: 10

1
In [7]: cxx"""
void printme(int x) {
std::cout << x << std::endl;
}
"""

Out[7]: true

In [8]: @cxx printme(jnum)

10

1.3 Passing strings from Julia to C++


In [9]: cxx"""
void printme(const char *name) {
// const char* => std::string
std::string sname = name;
// print it out
std::cout << sname << std::endl;
}
"""

Out[9]: true

In [10]: @cxx printme(pointer("John"))

John

1.4 Passing a Julia expression to C++


In [11]: cxx"""
void test_print() {
$:(println("\nTo end this test, press any key")::Void);
}
"""

Out[11]: true

In [12]: @cxx test_print()

To end this test, press any key

2
1.5 Embedding C++ code inside a Julia function
In [14]: function playing()
for i = 1:5
icxx"""
int tellme;
std::cout << "Please enter a number: " << std::endl;
std::cin >> tellme;
std::cout << "\nYour number is " << tellme << "\n" << std::endl;
"""
end
end

Out[14]: playing (generic function with 1 method)

In [15]: playing()

Please enter a number:

Your number is 32743

Please enter a number:

Your number is 32743

Please enter a number:

Your number is 32743

Please enter a number:

Your number is 32743

Please enter a number:

Your number is 32743

1.6 Using C++ enums


In [16]: cxx"""
class Klassy {
public:
enum Foo { Bar, Baz };
static Foo exec(Foo x) { return x; }
};
"""

Out[16]: true

3
In [17]: @cxx Klassy::Bar

Out[17]: Cxx.CppEnum{Symbol("Klassy::Foo"),UInt32}(0x00000000)

In [18]: @cxx Klassy::exec(@cxx Klassy::Baz)

Out[18]: Cxx.CppEnum{Symbol("Klassy::Foo"),UInt32}(0x00000001)

1.7 C++ classes


In [19]: cxx"""
#include <iostream>
class Hello {
public:
void hello_world(const char *now) {
std::string snow = now;
std::cout << "Hello, World! Now is " << snow << std::endl;
}
};
"""

Out[19]: true

In [20]: hello_class = @cxxnew Hello()

Out[20]: (class Hello *) @0x0000000008d62b80

In [21]: tstamp = string(Dates.now())

Out[21]: "2018-07-19T17:59:05.925"

In [22]: @cxx hello_class->hello_world(pointer(tstamp))

Hello, World! Now is 2018-07-19T17:59:05.925

You might also like