I am using a 3rd-party static library implemented in C++. I'm wrapping that object in a custom ObjC object in h
and mm
files, basically following the method described here. Many of the functions in the library return C-style arrays of int
s or double
s. So, for example, in thirdParty.h / .cpp:
const double * getCoefficients()
My wrapper code in myThirdPartyWrapper.mm then looks something like:
@interface myThirdPartyWrapper ()
{
thirdPartyObject *wrappedObj;
}
@end
@implementation myThirdPartyWrapper
- (id)init
{
self = [super init];
if (self)
{
// Create third-party object
wrappedObj = new thirdPartyObject;
if (!wrappedObj) self = nil;
}
return self;
}
- (void)dealloc
{
delete wrappedObj;
// Don't need [super dealloc] since we are using ARC
}
- (const double *)myGetCoefficients
{
return wrappedObj->getCoefficients();
}
And, back in my .m file:
myThirdPartyWrapper *wrapper = [[myThirdPartyWrapper alloc] init];
const double *coeff = [wrapper myGetCoefficients];
// etc...
This seemed to work OK for me for functions returning a double *
but crashed when returning a double **
. Then I read that it is not safe to return C-style arrays in objective-C because the memory pointed to by the local variables in the function are freed by ARC, so (in my example) coeff
would point to nothing. So instead I should do something like:
- (NSArray *)myGetCoefficients
{
double *Carray = wrappedObj->getCoefficients();
NSArray *array = [[NSArray alloc] init];
for (int i = 0; i < numItems; i++)
[array addObject:[NSNumber numberWithDouble:Carray[i]]];
return array;
}
My questions:
Is it a fluke that I'm not getting errors/crashes for functions that return
double *
or is this OK for some reason?The bigger question: Why does it even work to convert to
NSArray
? Why doesn't ARC free the memory created inwrappedObj->getCoefficients()
so thatCarray
becomes unusable inmyGetCoefficients
?