Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrapping C++ objects #3167

Closed
schmurfy opened this issue Jun 29, 2016 · 3 comments
Closed

Wrapping C++ objects #3167

schmurfy opened this issue Jun 29, 2016 · 3 comments

Comments

@schmurfy
Copy link
Contributor

When you are wrapping a C structure you can use mrb_malloc so there is no issue but how would you do it for a C++ object ? If I use new it won't be allocated on the mruby stack and if I use mrb_malloc the C++ specifc stuff won't be done...

In c I do it like this where manager_state is my c structure:

static mrb_value _initialize(mrb_state *mrb, mrb_value self)
{
  struct manager_state *st = (struct manager_state *)mrb_malloc(mrb, sizeof(struct manager_state));
  // [...]
}

I would prefer avoiding C++ entirely but that is not an option here.

@Moon4u
Copy link

Moon4u commented Jun 29, 2016

You can write your own new and delete functions that will be executed instead of the standard implementation. In your implementation use mrb_malloc and mrb_free.

@kyab
Copy link
Contributor

kyab commented Jun 29, 2016

I'm using "placement new" to create instance of C++ Class in mruby-arduino mrbgem.
Placement new allows you to use specific address (ex. memory area obtained by mrb_malloc), for instance.

  void *p = mrb_malloc(mrb, sizeof(Foo));
  Foo *foo = new(p) Foo();

https://github.com/kyab/mruby-arduino/blob/master/src/chipKITMax32_ArduinoDue.cpp#L57

@schmurfy
Copy link
Contributor Author

schmurfy commented Jul 4, 2016

thanks for the answers I did not know about placement new, I will look into it.

@schmurfy schmurfy closed this as completed Jul 4, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants