0

I'm trying to pass a shared pointer into Obj-C via void* so it can keep a particular object and then delete it (via C++ function).

Does this work?

I'm fine for a better idea, but this seems like the fastest way to get a reference to a shared pointer. Just want to make sure my math isn't off on the malloc (as I don't often use it).

std::shared_ptr<AAA> shared_ptr = getSharedPointer();
std::shared_ptr<AAA>* ptr = malloc(sizeof(std::shared_ptr<AAA>));
*ptr = shared_ptr;
return ptr;
user1122069
  • 1,767
  • 1
  • 24
  • 52
  • 2
    malloc with a shared ptr? Don't ever do that. – drescherjm Jan 07 '16 at 01:54
  • How will Obj-C delete said pointer? Use it? – Yakk - Adam Nevraumont Jan 07 '16 at 01:56
  • 1
    I don't understand what you're trying to do but it doesn't seem right. – 5gon12eder Jan 07 '16 at 01:57
  • It may be that Obj-C provides functionality that can make this easier, but the general solution is to give the other language an object pointer plus getref, addref and removeref functions. You **don't** give it a pointer to the implementation details of a C++ shared_ptr – Cheers and hth. - Alf Jan 07 '16 at 01:57
  • Never used `Obj-C` but I would imagine the only thing you could pass to it would be the *raw pointer* obtained through `shared_ptr.get()`. – Galik Jan 07 '16 at 01:58
  • @Galik It would not be possible to use the shared pointer in Obj-C, only to hold on to it and pass it back to C++ to be deleted. This is possible via "pointer to void" void*. As to passing a reference to a shared ref, this is possible only if the object is moved to the heap, and understood that the ref-count does not change when the pointer ref is copied, but stays at 1. – user1122069 Jan 08 '16 at 06:20
  • Here is not a bad alternative (http://stackoverflow.com/questions/1482806/manually-incrementing-and-decrementing-a-boostshared-ptr), but I like this method much better. – user1122069 Jan 08 '16 at 06:22
  • @drescherjm: Actually, `shared_ptr` _can_ work with `malloc`, the bug is forgetting the customer deleter which calls `free`. – MSalters Jan 08 '16 at 09:30

1 Answers1

0

Found via a search for malloc and c++ (Using malloc instead of new, and calling the copy constructor when the object is created)

Assignment works correctly as in the code in the OP, but it is then required to call the destructor manually and free() instead of delete.

I have tested with simple unit test that this works and the pointer reference counts are correctly incremented and decremented.

Community
  • 1
  • 1
user1122069
  • 1,767
  • 1
  • 24
  • 52