Question

I am developing a library which have C interface for compatibility purpose

void interface(double* context, size_t num_elements);

while context points to a raw memory storing num_elements doubles. In the remaining part of the code, is there any strategies to construct a std::valarray which temporarily manage the context without freeing it after the library call is over?

Was it helpful?

Solution

Couldn't you create a simple container to suit your needs? Here is a small example I didn't test:

template <class T>
class custom_valarray
{
public:

    // Ctor/dtor
    custom_valarray() { clear(); }
    ~custom_valarray() { clear(); }
    custom_valarray( T *ptr, const unsigned &s ) { set(ptr,s); }

    // Clear container
    void clear() { data = nullptr; size = 0; }

    // Set data
    void set( T *ptr, const unsigned &s ) { data = ptr; size = s; }

    // Test if container is set
    operator bool() const { return data; }
    bool empty() const { return data; }

    // Accessors
    T* data() { return data; }
    T& operator[] ( const unsigned &i ) 
    { 
        static T garbage;
        return i < size ? data[i] : garbage; 
    }

    // Iterators
    T* begin() { return data; }
    T* end() { return data+size; }

private:

    T *data;
    unsigned size;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top