How to assign dispatch_queue_t to variable in a structure - c++

I'm still relatively new to Objective C and easily confused by the various types. I am using code from the SquareCam sample project, incorporated into a larger project. It works fine, but now I want to save the videoDataOutputQueue, which is of type dispatch_queue_t so that I can use it elsewhere in the project. It has to pass through some C++ code before finally ending up back in Objective C code. Therefore I am trying to add it to a structure that I already have, as a void * (void *videoDataOutputQueue;)
However, I have not found the right way to assign it without getting a EXC_BAD_ACCESS runtime error. Since dispatch_queue_t is a C++ object, can't I just use it's address?
declared in the interface for squarecamviewcontroller:
#interface SquareCamViewController : UIViewController <UIGestureRecognizerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate,UIActionSheetDelegate>
{
AVCaptureVideoPreviewLayer *previewLayer;
AVCaptureVideoDataOutput *dataOutput;
AVCaptureVideoDataOutput *videoDataOutput;
dispatch_queue_t videoDataOutputQueue;
<other stuff>
}
later in the code:
- (void)setupAVCapture
{
<other stuff from the sample code>
MYSTRUCT myStruct = (MYSTRUCT)struct; // make a pointer to the structure
myStruct->videoDataOutputQueue = (void *)videoDataOutputQueue; <<<- bad access here at runtime
<other stuff>
}
Clearly this is not the right way and I don't understand what I am doing. I have some hints from other posts but I'm missing something.
Thanks,
Ken

You have made your question unnecessarily difficult to understand because the "code" you've presented has syntax errors. It's clearly not your real code, so we can't guess what's really supposed to be happening. For example, you use the struct reserved keyword as though it were a value.
Given where you say the bad access occurs, this has nothing to do with the dispatch queue. It looks like your myStruct variable is supposed to be a pointer to a structure of some kind but is just a garbage pointer. So, the attempt to assign a value to one of its fields ends up writing to an invalid memory address. It doesn't really matter what the nature of the field is.
The problem is apparently exactly in the code you omitted as "<other stuff from the sample code>". So, you need to show that. Indeed, you need to show your real code.
Beyond that, dispatch_queue_t is a C type. It's not specific to Objective-C. Therefore, you can use it across all C-based languages. There's no need to use a void*.
A dispatch queue, like all dispatch objects, is reference counted. If you're keeping a long-term reference to it, you need to make sure it stays alive. So, you need to retain it with dispatch_retain(). Likewise, you need to release it when you're done with it using dispatch_release(). (Don't forget to release the old value when you replace a reference you're keeping with another.)

Related

Refactor int to array, safely

Disclaimer: I'm unsure if this questions fits this forum, but it might.
Preamble: This question is about a project in C++98 and has mixed C and C++ sources. It also has global variables, and a lot of bad code.
I have a large code base (an old one) with an int theVar[] variable which represents a property of an object which is a collection. The model used to have only one instance of "the object". A new requirement came along which called for having more than one instance of the object, so I had to refactor this int[] into an int[][], where the first index specified the instance of the object. Changing the type of the variable in the declaration allows the compiler to warn me of places in the code in need of updating, but it misses things such as:
if (theVar[i]) ...
And more.
How can I perform this refactoring in the safest way?
NOTE
There is some really good advice in the comments, I appreciate it, this question might not have a best answer, but the comments have given me some good directions to follow.

How to cast const FB::variant& into user defined class in c++?

I am tryintg to cast const FB::variant& sample into SampleJS* in C++.
like this:
SampleJS* info = sample.cast<SampleJS*>();
i do not know what is going wrong here.
this gives me error of:
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >
Thank you in advance.
You need to understand that FB::variant just stores whatever type is put into it. Your code will absolutely work... if what is inside happens to be a MouseInfoJS*. However, you'd have to go through a lot of work to put something like that inside, since the FB::variant class is designed to make it difficult, but not impossible, to store inside it types that it doesn't know.
So basically, what you're trying to do probably doesn't make any sense, so you can't do it.
Depending on what type MouseInfoJS is, it might sorta make sense. Does MouseInfoJS inherit from JSAPI? (or JSAPIAuto?) If so, then it would somewhat make sense to try what you're doing, except that you'd never have a MouseInfoJS*, you'd have a MouseInfoJSPtr, which would be a typedef for boost::shared_ptr, since it would then be partially owned by the page and thus dangerous to store a raw pointer there.
Even in this case, which you'd need to use .convert_cast<MouseInfoJSPtr>, not .cast, it won't work on most modern browsers because they wrap the NPObject returned by FireBreath in another object which doesn't allow us to get the original object back; I believe this is a security feature. For more information, see A firebreath JSAPI will not be recognized in firefox

C++: use of “().” and “()[].”

I am trying to understand the programming of Siemens scanner using C++ and given that my C++ skills are limited, I am having problems in understanding many parts of the code provided by the vendor.
Problem 1
For instance, the code uses reference (rMrProt) to object MrProt and notations (such as the use of use of (). and ()[].) are very confusing to me.
For instance:
ImageSamples = rMrProt.kSpace().baseResolution()
ImageSize = rMrProt.sliceSeries()[0].readoutFOV()
Some explanation of these statements would be appreciated.
All information regarding object MrProt are in “MrProt.h”, “MrProt.dll”, “MrProt.lib”. All these files have been shared at:
https://docs.google.com/open?id=0B0Ah9soYnrlIYWZkNDU2M2EtYTNmNC00YTc5LTllMzItYzIyMWU4M2ZhY2Fi
Problem 2
Also, I have been trying to read MrProt.dll and MrProt.lib without any success. Only now, I came to know of dumpbin. Any help would be appreciated.
Problem 3
Another confusion that I have is related to some part of MrProt.h itself. There is a statement in MrProt.h:
class __IMP_EXP MrProt: public MrProtocolData::MrProtDataDelegate
{
typedef MrProtocolData::MrProtDataDelegate BasicImplementation;
public:
MrProt();
MrProt(const MrProt& rSource);
…
….
}
Here, __IMP_EXP, I guess that it’s some compiler specific stuff.. some decoration etc. But, I still have no idea what to make of this.
Problem 1.
rMrProt.sliceSeries()[0].readoutFOV()
means
Take rMrProt's sliceSeries member and call that. Apparently, it returns an array-like object, something that can be indexed.
From the result, take the first element ([0]). That's some kind of object.
On that element/object, call readoutFOV.
Problem 2. You're not really supposed to read binary files. There should be documentation with them.
1)
ImageSamples = rMrProt.kSpace().baseResolution()
This is just method chaining. You call the method kSpace() on rMrPrto which returns an object, and you call baseResolution() on that object.
2) Those are binary files. What would you expect to see? To read them you'd have to be an expert in asm or at least know some low-level concepts.
3) __IMP_EXP is a common type of directive that tells the compiler that the class is either exported or imported.
It expands to _declspec(dllimport) or _declspec(dllexport), depending on whether the definition of the class is in the current module or another module.
identifier() is a method/function call
identifier[i] returns the i'th element in an array.
identifier()[i] returns the i'th element of the array returned by identifier()
I can only help on problem 1:
if the return value of rMrProt.kSpace() is a struct. instead of saving it to a struct and then access it's member you can directly access a member of his with rMrProt.kSpace().MemberName
same for rMrProt.sliceSeries() which I guess is returning an array. so rMrProt.sliceSeries()[0] will access the first value in the returning array.

How to get rid of void-pointers

I inherited a big application that was originally written in C (but in the mean time a lot of C++ was also added to it). Because of historical reasons, the application contains a lot of void-pointers. Before you start to choke, let me explain why this was done.
The application contains many different data structures, but they are stored in 'generic' containers. Nowadays I would use templated STL containers for it, or I would give all data structures a common base class, so that the container can store pointers to the base class, but in the [good?] old C days, the only solution was to cast the struct-pointer to a void-pointer.
Additionally, there is a lot of code that works on these void-pointers, and uses very strange C constructions to emulate polymorphism in C.
I am now reworking the application, and trying to get rid of the void-pointers. Adding a common base-class to all the data structures isn't that hard (few days of work), but the problem is that the code is full of constructions like shown below.
This is an example of how data is stored:
void storeData (int datatype, void *data); // function prototype
...
Customer *myCustomer = ...;
storeData (TYPE_CUSTOMER, myCustomer);
This is an example of how data is fetched again:
Customer *myCustomer = (Customer *) fetchData (TYPE_CUSTOMER, key);
I actually want to replace all the void-pointers with some smart-pointer (reference-counted), but I can't find a trick to automate (or at least) help me to get rid of all the casts to and from void-pointers.
Any tips on how to find, replace, or interact in any possible way with these conversions?
I actually want to replace all the
void-pointers with some smart-pointer
(reference-counted), but I can't find
a trick to automate (or at least) help
me to get rid of all the casts to and
from void-pointers.
Such automated refactoring bears many risks.
Otherwise, sometimes I like to play tricks by making out of such void* functions the template functions. That:
void storeData (int datatype, void *data);
becomes:
template <class T>
void storeData (int datatype, T *data);
At first implement template by simply wrapping the original (renamed) function and converting the types. That might allow you to see potential problems - already by simply compiling the code.
You probably don't need to get rid of the casts to use shared pointers.
storeData(TYPE_CUSTOMER, myCustomer1->get());
shared_ptr<Customer> myCustomer2(reinterpret_cast<Customer*>fetchData(TYPE_CUSTOMER, "???");
Of course, this assumes that you don't expect to share the same pointer across calls to store/fetch. In other words, myCustomer1 and myCustomer2 don't share the same pointer.
Apparently, there is no automated way/trick to convert or find all uses of void-pointers. I'll have to use manual labor to find all void-pointers, in combination with PC-Lint that will give errors whenever there is an incorrect conversion.
Case closed.

The ** idiom in C++ for object construction

In a lot of C++ API'S (COM-based ones spring to mind) that make something for you, the pointer to the object that is constructed is usually required as a ** pointer (and the function will construct and init it for you)
You usually see signatures like:
HRESULT createAnObject( int howbig, Object **objectYouWantMeToInitialize ) ;
-- but you seldom see the new object being passed as a return value.
Besides people wanting to see error codes, what is the reason for this? Is it better to use the ** pattern rather than a returned pointer for simpler operations such as:
wchar_t* getUnicode( const char* src ) ;
Or would this better be written as:
void getUnicode( const char* src, wchar_t** dst ) ;
The most important thing I can think of is to remember to free it, and the ** way, for some reason, tends to remind me that I have to deallocate it as well.
"Besides wanting error codes"?
What makes you think there is a besides. Error codes are pretty much the one and only reason. The function needs some way to indicate failure. C doesn't have exceptions, so it has to do that through either a pointer parameter, or the return value, and the return value is idiomatic, and easier to check when calling the function.
(By the way, there's no universal rule that ** means you have to free the object. That's not always the case, and it's probably a bad idea to use something that arbitrary to remind you of which objects to clean up.)
Two reasons come to my mind.
First are error codes actually. Other than C++, C doesn't have exceptions, and COM is a C-API. Also many C++ based projects prefer not to use exceptions for various reasons.
There may be cases, where a return value can't signal errors, E.g. if your function returns an integer, there may be no integer value, that can represent an error code. While signalling errors with pointers is easy (NULL == Error), some API designers prefer to signal errors in a consistent way over all functions.
Second, functions can have only one return value, but calling them may create multiple objects. Some Win32 API functions take multiple pointers to pointers that can be filled optionally, if you call these functions with non-NULL pointers. You cannot return two pointers, or rather this would be awkward to use, if the return value is some struct by value containing more than one pointer. Here too a consistent API is a sensible goal to achieve.
New objects in function arguments passed by ** is better. This take me a comfort to future use of change void to bool for example to return success of a function or other information providing function works.
Answer in one line: This is much better for resulting error codes.
Besides people wanting to see error codes, what is the reason for this?
There are some reasons for this. One of them is writing an interface that is usable in C (you see this in the WinAPI and Windows COM).
Backwards compatibility is another reason (i.e. the interface was written like that and breaking it now would break existing code).
I'd go with C compatibility for a design principle when using code like this. If you were to write in C++ you'd write
retval Myfunction(Result *& output);
instead of
retval Myfunction(Result ** output);
or (even better):
Result *Myfunction();
and have the function throw an exception on error.
I'm not sure I agree that's the best way to do it... this might be better:
Object * createAnObject(int howbig, HRESULT * optPlaceResultCodeHereIfNotNull = NULL);
That way there is no messing about with double-indirection (which can be a little bit tricky for people who aren't used to it), and the people who don't care about result codes don't have to worry about the second argument at all... they can just check to see if the return value is NULL or not.
Actually, since it's C++, you could make things easier still, using function overloading:
Object * createAnObject(int howbig);
Object * createAnObject(int howbig, HRESULT & returnResultCode);
Any method call in a COM call has to be HRESULT. The return codes get leveraged all over the framework and passing a double pointer is a well-known way to get the created object.
Not answering your question but a comment as your question brought out some thoughts I have about COM/DCOM programming using C++.
All these "pointer" and "pointer to pointer", memory management and reference counting are the reasons why I shy away from doing COM programming with C++. Even with ATL in place, I dislike it for the simple reason that it does not look natural enough. Having said that, I did do a few projects using ATL.
Back then the alternative is use VB. VB code looks more natural for COM or DCOM programming.
Today, I would use C#.