Getstring (lxu_getstring.hpp)

From The Foundry MODO SDK wiki
Jump to: navigation, search

Strings are passed through interfaces in two ways. When the string is owned by the object the method can return a char pointer to the stored string. In cases when a string result is computed the caller passes a char buffer and size, and the interface fills in the buffer with the result. If the buffer is too small the interface returns the LXe_SHORTBUFFER error.

Naturally on the C++ side we want to treat strings as std::string objects. These utility classes manage the conversions.

CLxSafeGetString

This template class encapsulates reading a string from an interface by passing allocated buffers of increasing size until it succeeds. This is normally used by user classes to make safe std::string versions of buffer/size interfaces.

By way of example, here's the code for the String() method of the Attributes user class. The CLxSafeGetString template class is initialized with a class containing an sgs_GetString() method which takes a buffer and length to receive the string. If the buffer is too short it must return LXe_SHORTBUFFER, and the SafeGetString class will continue to call it with longer buffers until it succeeds. Since the Attributes::GetString() method requires an index, we use a temporary intermediate class to do the conversion.

class Tmp_Sgs {
    public:
        CLxLoc_Attributes	*attr;
        unsigned		 index;

        LxResult sgs_GetString (char *buf, unsigned int len)
        {
                return attr->GetString (index, buf, len);
        }
};

        bool
CLxUser_Attributes::String (
        unsigned		 index,
        std::string		&text)
{
        Tmp_Sgs				 tmp;
        CLxSafeGetString<Tmp_Sgs>	 sgs;

        tmp.attr  = this;
        tmp.index = index;
        return sgs.GetStringBool (tmp, text);
}

lx::StringOut()

This utility function allows a std::string to be returned from methods that use the buffer/size protocol. The string is copied to the buffer and if too small it returns LXe_SHORTBUFFER. This is the other side of the safe-string transaction.

	LxResult
CInstance::pins_SynthName (
	char			*buf,
	unsigned		 len)
{
	std::string		 result;

	... // compute result string
	return lx::StringOut (result, buf, len);
}