1

I am working on a COM-style complier cross-compatible plugin framework relying on compatible virtual table implementations for ABI compatibility. I define interfaces containing only pure virtual member functions and an overridden delete operator to channel destruction to the place of implementation. This works well with extern "C" factory functions instantiating the plugin implementation of the interface and returning an interface-type pointer.

However, I was wondering if smart pointers wouldn't be a more modern way to manage the lifetime of the plugin object. I think I have actually managed to create a standard-layout shared_ptr/weak_ptr that uses a reference count object defined and implemented the same way as the plugin interfaces. It looks something like this:

class IRefCount
{
public:
  virtual void incRef() = 0;
  virtual void decRef() = 0;
  virtual bool incRefIfNZ() = 0;
  virtual void incWRef() = 0;
  virtual void decWRef() = 0;
  virtual long uses() const = 0;
protected:
  ~ref_count_base() = default; //prohibit automatic storage
}
template <typename Ty>
class shared_ptr
{
private:
   Ty* ptr_;
   IRefCount* ref_count_;
public:
   //member functions as defined by C++11 spec
}

Three questions:

Before the smart pointer the factory function looked like this:

extern "C" IPlugin* factory() { try { return new Plugin(); } catch (...) { return nullptr; } }

Now, it looks like this:

extern "C" shared_ptr<IPlugin> factory() { try { return shared_ptr<IPlugin>(new Plugin()); } catch (...) { return nullptr; } }

VS2013 is giving me warning C4190: 'factory' has C-linkage specified, but returns UDT 'shared_ptr' which is incompatible with C. According to MSDN this is OK, provided that both caller and callee are C++.

  1. Are there any other potential issues with returning standard-layout objects from "C" linkage functions?

  2. Calling conventions. Should I be specifying __stdcall for all pure-virtual interface functions and factory functions?

  3. I am using <atomic> for the reference count. I am writing platform-independent code and I have not yet tried compiling for ARM. According to http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dht0008a/ch01s02s01.html armcc does not implement std::atomic. Any better compilers/stl out there?

Mart
  • 135
  • 1
  • 10

0 Answers0