JuliaInterop / libcxxwrap-julia

C++ library for backing CxxWrap.jl
Other
84 stars 43 forks source link

Add a class embedding example #110

Open MariusDrulea opened 1 year ago

MariusDrulea commented 1 year ago

Not really an issue, but it would be nice to have an embedding example of Julia into C++. This is an absolute need in large c++ projects as it's easier to embed julia in a sub-project, rather than wrapping the entire C++ project for julia. I have the impression this is already possible with the existing libcxxwrap-julia framework.

Let's say we have a class like the one you use in types.cpp. Of course, we would like to work with World in both Julia and C++.

struct World
{
  World(const std::string& message = "default hello") : msg(message){}
  void set(const std::string& msg) { this->msg = msg; }
  const std::string& greet() const { return msg; }
  std::string msg;
  ~World() { std::cout << "Destroying World with message " << msg << std::endl; }
};

Here are two sample julia functions:

function say(w::World)
       return w.greet()
end

function better(w::World)::World
      return World(greet(w) * " happy people")
end

We have an object of the class World already initialized by C++ and we would like to pass this object to the above julia functions to do some work. Now we want these julia functions to be called by c++. How can we do this?

int main()
{
    w = World("hello");
    s = // how to call the julia method say with the c++ object w as parameter.
    std::cout << s << std::endl;

    bw = //how to call the julia method better with the c++ object w as parameter
    std::cout << greet(bw) << std::endl;
}