Do STL containers support ARC when storing Obj-C objects in Objective-C++? - stl

For example, would this leak?
static std::tuple<CGSize, NSURL *> getThumbnailURL() {
return std::make_tuple(CGSizeMake(100, 100), [NSURL URLWithString:#"http://examples.com/image.jpg"]);
}

No, it wouldn't leak. That NSURL object would be managed by ARC properly.
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#template-arguments
If a template argument for a template type parameter is an retainable object owner type that does not have an explicit ownership qualifier, it is adjusted to have __strong qualification.
std::tuple<CGSize, NSURL *> is the same as std::tuple<CGSize, NSURL __strong *>. Thus NSURL object will be released when the std::tuple instance is destructed.

Yes, they work. STL containers are templated (STL = Standard Template Library), so whenever you use one it's as if you re-compiled their source code with the template arguments substituted in (template instantiation). And if you re-compiled their source code with the template arguments substituted in, then ARC would perform all the appropriate memory management necessary for the managed pointer types in that code.
Another way to think about it is that ARC managed pointer types are actually C++ smart pointer types -- they have a constructor that initializes it to nil, an assignment operator that releases the existing value and retains (or for block types, copies) the new value, and a destructor that releases the value. So as much as STL containers work with similar C++ smart pointer types, they work with ARC managed pointer types.

Related

How to write C++ constructor of cython extension type?

How do I modify the C++ class constructor that cython will generate from a Cython extension type that I've defined in a .pyx file wo that I don't incur the penalty of using def __cinit__(self)? Assume I am compiling to C++, not C.
What I would like to do is set the default values as I would in an initialization list in C++, and maybe run some code in the constructor without interacting with Python. It looks like the __cinit__ method runs after the C++ class members are initialized and the C++ constructor finishes running.
In this example, it says
Cython initializes C++ class attributes of a cdef class using the nullary constructor.
I assume this refers to the default constructor since the C++ constructor is a nullary constructor. I also assumes this happens with or without a __cinit__ method.
If the class you’re wrapping does not have a nullary constructor, you must store a pointer to the wrapped class and manually allocate and deallocate it. A convenient and safe place to do so is in the cinit and dealloc methods which are guaranteed to be called exactly once upon creation and deletion of the Python instance.
I have an existing class where I call Py_XDECREF on a member object in a loop inside of __dealloc__. This object holds pointers to Python objects. When I convert to C++ code, the annotated HTML shows no highlighted yellow text in the lines where the __dealloc__ method is defined. This is interesting because __dealloc__ is also defined using def.
When I try to initialize a member that is an instance of a Cython Extension that I defined (and did not create from wrapping C++ code), however, the __cinit__ method is highlighted in yellow.
def __cinit__(self):
self._member = MyCyExt()
I'm wondering if it's because I can't initialize a Cython Extension Type in pure C++. I don't know why that would be the case since Cython calls the nullary constructor by default.
This answer solves the problem, but it incurs the overhead I am trying to avoid. Is there a way to do this without incurring that overhead and actually writing the constructor itself in a .pyx file?

How to instantiate H264 Encoder on WinRT Store App

I want to be able to encode video frames using Media Foundation IMFTransform for H264 Video Encoding. That's easily doable in Win32, where you can use MFTEnumEx to enumerate the transforms and find the H264 encoder.
However, on WinRT (Store Apps), I can't find a way to instantiate.
I've noticed there's a class CMSH264EncoderMFT, but there's no definition for the CLSID to use on CoCreateInstance.
With:
CoCreateInstance(CLSID_CMSH264EncoderMFT, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IUnknown), (void **)&pUnknown);
CLSID_CMSH264EncoderMFT is undefined for WinRT apps.
And tried:
ComPtr<CMSH264EncoderMFT> encoder = Make<CMSH264EncoderMFT>();
It says the class CMSH264EncoderMFT is incomplete, and says "use of undefined type 'CMSH264EncoderMFT'". Don't even know if the syntax for Make is correct or appropriate...
Does anyone have a clue on how to do this for WinRT?
Use MFCreateSinkWriterFromURL to create a file writer first. Then, use MFCreateMediaType to create an IMFMediaType. Set up its properties, one of which will be the output format: use SetGUID method on the media type with MF_MT_SUBTYPE guid and specify MFVideoFormat_H264 as the argument. Finally, use AddStream method on the sink writer to set the media type to it.
There's an example here (you'll need to modify it a bit when it sets MF_MT_SUBTYPE).
you cannot instantiate object via CMSH264EncoderMFT because it DOES NOT have some interfaces which MUST have object in WinRT for example IInspectable - Provides functionality required for all Windows Runtime classes. CMSH264EncoderMFT IS NOT WinRT class. You can try resolve your task by function MFCreateSinkWriterFromMediaSink - this function takes an object with interface IMFMediaSink. It is possible write code for object with IMFMediaSink interface and receive samples from IMFTransform::ProcessOutput. I just point your attention - you cannot instantiate in WindowsStore code objects which IS NOT Windows Runtime classes.
Regards,
Evgeny Pereguda

How do we wrap C++ variable argument parameter in WinRT components

I have a C++ method that takes variable argument as init param. Something like
MyMethod(std::wchar_t*, ...)
Can someone please let me know how can we write a WinRT component wrapper to expose the variable arguments?
WinRT metadata does not support vararg functions, so there is no good way to do this. The answer therefore depends on what the function actually does. Assuming it is some kind of string formatting function I would suggest wrapping it with something like:-
MyMethod(Platform::String^, Windows::Foundation::Collections::IVector<Platform::Object^>^ params);
This will allow you to take the variable arguments.
The problem of course is that this has completely different semantics from what you have. The caller is going to have to pack up an array, and you won't be able to call your existing method easily with the arguments from the vector.

BlackBerry - Exception when creating a graphics object from a bitmap

I am making the following call in my blackberry application (API ver 4.5)...
public void annotate(String msg, EncodedImage ei)
{
Bitmap bitmap = ei.getBitmap();
Graphics g = new Graphics(bitmap);
g.drawText(msg,0,0);
}
And I keep getting an IllegalArgumentException when I instantiate the Graphics object. Looking at the documentation for Graphics is confusing as it leaves many things unstated.
What does it mean by 'default type of the device'?
How do you know if the type of 'bitmap' is not supported? Does this mean that there are different types of bitmaps? Can different encodedImages generate different types of bitmaps?
Is there another way to add my string to the associated encoded image?
public Graphics(Bitmap bitmap)
Constructs a Graphics object for drawing to a bitmap.
Parameters:
bitmap - Bitmap to draw into. Must be Bitmap.COLUMNWISE_MONOCHROME or the default type of the device.
Throws:
IllegalArgumentException - If the type of 'bitmap' is not supported, or the bitmap is readonly.
Are you sure that your Bitmap is mutable? You can't create Graphics objects from immutable Bitmaps. That is one cause of an IllegalArgumentException. You can set the decode mode for your EncodedImage (EncodeImage.setDecodeMode). There are different modes that allow you to specify whether the file is native or readonly...along with other modes that can be combined.
The size of the bitmap might be another IllegalArgumentException. Of course, this is relevant to the target device.
I'd imagine that the default type depends on the graphics chip and hardware. (If you have a monochrome screen, the default would probably be different than if you had a color one.)
Bitmap has a static method getDefaultType(), which "Queries the default Bitmap type for the device". There's also a non-static method getType(). It seems to be telling you the rule is that for the code above to work then either:
bitmap.getType() == Bitmap.getDefaultType()
...or...
bitmap.getType() == COLUMNWISE_MONOCHROME
And presumably neither of these conditions are true. You can do a sanity check on that, and maybe print out the result of getDefaultType() so you know what your target is.
Looks like you'll have to convert the bitmap or get it from somewhere else.
The Graphics object isn't normally constructed explicitly. Rather, you are given an instance of it in the paint() method, if you've overridden it.
I suspect what you want to do is create a subclass of BitmapField and override the paint() method to include your code for drawing text on the bitmap.

Whats the difference between C# delegates, Dynamic Proxy, Closures and function pointers?

What are useful definitions for the common methods of passing a method or function as data, such as:
Delegates
Closures
Function pointers
Invocation by dynamic proxy and
First class methods?
Function pointers lets you pass functions around like variables. Function pointer is basically legacy method to pass function around in languages that don't support first-class methods, such as C/C++.
First class methods Basically means you can pass functions around like variables. Methods (loosely) mean functions. So this basically means first class functions. In simplest terms, it means functions are treated as "first class citizens", like variables. In the old days (C/C++), because we can't directly pass a function around, and we had to resort to workarounds like function pointers, we said functions weren't first-class citizens.
Delegates is C#'s answer to first-class methods. Delegates are somewhat more powerful because it involves closures, consider the following code snippet:
void foo( int a )
{
void bar() { writefln( a ); }
call( &bar );
}
void call( void delegate() dg ) { dg(); }
int main( char[][] args ) {
foo( 100 );
}
Notice that bar can reference the local variable a because delegates can use closures.
Closures can be very confusing at first. But the lazy-man's definition can be really simple. It basically means a variable can be available in the human-expected way. Put in other words, a variable can be referenced in places where they look like they would be present, by reading the structure of the source code. For example, looking at the code fragment above. If we didn't have closure, bar would not be able to reference a because a was only local to foo, but not bar, which is another function.
Dynamic Proxy is the odd one out. It doesn't belong to these items. Explaining it requires some very long text. It stems from the famous Proxy Pattern. The problem with Proxy Pattern was that the Proxy class needs to be implementing the same interface as the Subject. Dynamic Proxy basically means using reflective approach to discover the Subject's method so that the ProxyPattern can be freed from being tied to the Subject's interface.
just the ones i know about:
Function pointers: just that, a pointer to a piece of code. you jump to it, it executes. typed languages can enforce some parameter passing convention (i.e. C declarations)
Closures: a function with some state paired. most naturally written in lexically scoped languages (i.e. Scheme, JavaScript, Lua). several closures can share the same state (or part of it), making it an easy way to implement OOP.
First class methods: a closure created from an object instance and a method. some languages with both closures and a native OOP (Python, JavaScript) can create closures automatically.
Closure is a programming language concept. Delegate is its realization in MS.NET.
A Delegate in MS.NET is a strongly typed pointer to an object's method (a delegate instance points to both - an object and its method). There is also a way to combine several void delegate instances into one.