Return dynamically allocated memory from C++ to C

前端 未结 10 2320
粉色の甜心
粉色の甜心 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条回答
  •  暖寄归人
    2021-01-01 07:43

    There are various methods, developed over time, to return a variable amount of data from a function.

    1. Caller passes in buffer.
      1. The neccessary size is documented and not passed, too short buffers are Undefined Behavior: strcpy()
      2. The neccessary size is documented and passed, errors are signaled by the return value: strcpy_s()
      3. The neccessary size is unknown, but can be queried by calling the function with buffer-length 0: snprintf
      4. The neccessary size is unknown and cannot be queried, as much as fits in a buffer of passed size is returned. If neccessary, additional calls must be made to get the rest: fread
      5. The neccessary size is unknown, cannot be queried, and passing too small a buffer is Undefined Behavior. This is a design defect, therefore the function is deprecated / removed in newer versions, and just mentioned here for completeness: gets.
    2. Caller passes a callback:
      1. The callback-function gets a context-parameter: qsort_s
      2. The callback-function gets no context-parameter. Getting the context requires magic: qsort
    3. Caller passes an allocator: Not found in the C standard library. All allocator-aware C++ containers support that though.
    4. Callee contract specifies the deallocator. Calling the wrong one is Undefined Behavior: fopen->fclose strdup->free
    5. Callee returns an object which contains the deallocator: COM-Objects std::shared_ptr
    6. Callee uses an internal shared buffer: asctime

    In general, whenever the user has to guess the size or look it up in the manual, he will sometimes get it wrong. If he does not get it wrong, a later revision might invalidate his careful work, so it doesn't matter he was once right. Anyway, this way lies madness (UB).

    For the rest, choose the most comfortable and efficient one you can.

提交回复
热议问题