@cxx in julia

julia> 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;
                          }
                  };
              """
true

julia> hello_class = @cxxnew Hello()
(class Hello *) @0x000000000726c190


julia> using Dates

julia> tstamp = string(Dates.now())
"2019-11-03T17:57:36.736"

julia> pointer(tstamp)
Ptr{UInt8} @0x00007f62dd088978

julia> @cxx hello_class->hello_world(pointer(tstamp))
Hello, World! Now is 2019-11-03T17:57:36.736

I do not quite get the very last line of code, i.e., @cxx hello_class->hello_world(pointer(tstamp)). Why do we use pointer(tstamp) here? Any comments are greatly appreciated.

C++ or C is not my strongest expertise area. Anyway, this is something you must do. The pointer gives you the pointer to the memory address and that information need to be passes to Cxx. All the communication between C++ and Julia is done using pointers.

3 Likes

Just to complement @Tero_Frondelius perfectly fine answer:

string(Dates.now()) will create something which in memory has the same layout as an std::string. This way your C++ application will understand its structure and can deal with it. The only thing you need to tell the function is where to look for the data as it was implemented to take a pointer to a memory location, as seen in its signature (const char *now).

That’s it. You ask Julia for the pointer and pass it.

Just think of a shared memory pool during runtime, which can be used by both the Julia and the C++ part. The intercommunication can done by passing around the memory address of those bytes. As long as you share data with known structures on both sides, they will work as expected.

1 Like