Return dynamically allocated memory from C++ to C

前端 未结 10 2125
粉色の甜心
粉色の甜心 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:58

    You have to allocate the string on the heap if you want to safely return it, also allocate with malloc() i.s.o. new() when writing C functions.

    When you return pointers (and, unlike in C++, in C you have no real choice many times), deallocation is always a concern. There isn't really a definitive solution.

    One way of handling this I've seen in quite some API's is calling all function either

    CreateString()
    

    When memory needs to be deallocated by the caller, and

    GetString()
    

    when that's not an issue.

    This is anything but foolproof of course, but given enough discipline it's the best method I've seen to be honest...

提交回复
热议问题