Return dynamically allocated memory from C++ to C

前端 未结 10 2309
粉色の甜心
粉色の甜心 2021-01-01 07:10

I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I\'m not sure on how to do this safely..

const char *Ge         


        
10条回答
  •  Happy的楠姐
    2021-01-01 07:35

    Over the years C boiled this down to 2 standard methods:

    • Caller passes in buffer.
      There are three versions of this.
      Version 1: Pass a buffer and a length.
      Version 2: Documentation specifies an expected min buffer size.
      Version 3: Pre-Flight. Function returns the min buffer required. caller calls twice first time with a NULL buffer.
      • Example: read()
    • Use a static buffer that is valid until the next call.
      • Example: tmpname()

    A few non standard ones returned memory that you had to explicitly free

    • strdup() pops to mind.
      Common extension but not actually in the standard.

提交回复
热议问题