Lua embedding in C ++ mixed with C

I am working on embedding Lua in a C ++ project, which relies heavily on some inherited C codes. I have a few questions regarding garbage collection and variable areas.

Below are some snippets related to the following issues:

/* C side */

typedef struct
{
  /* fields */
} Element;


typedef struct 
{
   void * m_elems
   unsigned int size;

} Container;

// C API for managing Container and Element
....
int   allocContainer(Container*, unsigned int);
void  freeContainer(Container*);
Element * getElemByIndex(unsigned int);



// C++ side
struct ElementWrapper
{
private:
  Element m_elem;

public:
  /* field accessors (NO modifiers) */
};


class ContainerWrapper
{
private:
ContainerWrapper m_cntnr;

public:
    ContainerWrapper(int N);  // allocates space for N elements
    ~ContainerWrapper();

    // stack alloc'ed variable
    ElementWrapper getElementAtIndexStackAllocated(unsigned idx) const;

    // heap alloc'ed variable
    ElementWrapper * getElementAtIndexHeapAllocated(unsigned idx) const;
};



-- Lua side
wrapper = Container:new(10)

for i =1,10 do
  -- get the ith element
  el_s = wrapper.getElementAtIndexStackAllocated(i)
  el_h = wrapper.getElementAtIndexHeapAllocated(i)

  -- do something with retrieved element ..
end
  • when are the el_s and el_h garbage collector variables collected?
  • Do I need to use the local keyword for el_s and / or el_h to make sure that the variables are discarded at the end of each iteration in the "for" loop?
  • Indexes start at 0 in the C / C ++ world, but 1 from Lua - do I need to know about this in my code, or is the tolua ++ code suitable for this code?

. (, boost: shared_ptr), C / .., , , Lua, -. Lua ( tolua ++), C . , ++ Lua GC. , C mem - - , - , Lua GC (, , , ). , raw ptrs .

+3
1

Lua , , - ( ). , el_h el_s , , local.

, , el_h, i= 1 , el_h , i= 2.

, tolua ++ , , , , C ++ .

, , tolua ++ , , . wrapper.getElementAtIndexStackAllocated() Lua, ++.

, " ". , , , , . collectgarbage("collect")

0

Source: https://habr.com/ru/post/1789185/


All Articles