c# - Casting COM types in C++ -
i have following com types: project
, containeritem
, node
. project
has collection property append
function accepts containeritem
s.
in c#, using type libraries can send node
object append
function , library works expected:
var prj = new project(); var node = new node(); prj.collection.append(node);
in c++ tried direct pointer cast expecting c# doing, ends in error:
projectptr prj; prj.createinstance(__uuidof(project)); nodeptr node; node.createinstance(__uuidof(node)); prj->collection->append((containeritem**)&node.getinterfaceptr());
is there specific way these type of com pointer casts in c++? missing?
com casting done queryinterface()
method. object queried support of interface (based on guid), , if interface supported, internal reference counter incremented (see addref()
) , pointer interface returned. msdn has more detail on inner workings.
c++ not directly support code generation "com cast" c# does, implementation simple enough.
struct bad_com_cast : std::runtime_error { bad_com_cast() : std::runtime_error("com interface not supported") {} }; template <class to, class from> to* qi_cast(from* iunknown) { hresult hr = s_ok; to* ptr = null; if (iunknown) { hr = iunknown->queryinterface(__uuidof(to), (void**)(&ptr)); if (hr != s_ok) { throw bad_com_cast(); // or return null } } return ptr; }
using above "cast", sample can implemented follows;
containeritem* ci = qi_cast<containeritem>(node); prj->collection->append(&ci);
if atl library being used, can use atl::ccomqiptr<>
directly obtain equivalent semantics;
auto ci = ccomqiptr<containeritem>(node); if (ci) { // ... }
Comments
Post a Comment