1

Suppose there is a function in a legacy library that I want to use that requires a function pointer as an input

void LegacyFunction(int* (*func)(float, float), int a, float b);

but the problem is it is expecting the return value of the function to be an int raw pointer instead of an int unique_ptr, meaning I can only get it to compile if my function looks like

int* MyFunc(float a, float b);

in other words, if I modify MyFunc into

std::unique_ptr<int> MyFunc(float a, float b);

and pass it into the legacy library function like

LegacyFunction(MyFunc, 1, 2.0f);

there will be a compilation error. I know if the function is taking an usual int pointer there can be some workaround using the get() function like

std::unique_ptr<int> a;
LegacyFunctionRawPointer(a.get(), 1, 2.0f);

Is there a similar workaround for function pointer input? It will be a travesty if I have to replace the unique_ptr for MyFunc with raw pointer.

7
  • Is MyFunc a runtime value or is it known at the compile time? Commented Nov 7, 2016 at 22:58
  • 1
    Who owns the pointer? Is legacy library the owner? Does legacy library destroy the pointer? Commented Nov 7, 2016 at 22:58
  • A simple lambda function wrapper seems like it would work, but you'd have memory leaks if the legacy didn't free the memory returned in the same way it was allocated. Commented Nov 7, 2016 at 22:59
  • You could wrap MyFunc in a lambda. Commented Nov 7, 2016 at 22:59
  • @krzaq it's known at compile time Commented Nov 7, 2016 at 23:05

1 Answer 1

5

A lambda function should work, e.g.:

LegacyFunction([](float a, float b) { return MyFunc(a, b).release(); }, 1, 2.0f);

but only if LegacyFunction will naturally delete/free the memory that MyFunc allocated with the appropriate operation (so if MyFunc used new int, LegacyFunction must use delete retval;; if it used new int[x], it must use delete[] retval;).

The release method gets the contained pointer and relinquishes ownership, so you've explicitly given up unique_ptr's protections; not a great idea if you can avoid it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.