Return dynamically allocated memory from C++ to C

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

    The answers so far don't address a very significant issue, namely what to do if the length of the required buffer for the result is unknown and can change between calls, even with the same arguments (such as reading a value from a database), so I'm providing what I consider to be the best way to handle this situation.

    If the size is not known in advance, consider passing a callback function to your function, which receives the const char* as a parameter:

    typedef void (*ResultCallback)( void* context, const char* result );
    
    void Foo( ResultCallback resultCallback, void* context )
    {
         std::string s = "....";
         resultCallback( context, s.c_str() );
    }
    

    The implementation of ResultCallback can allocate the needed memory and copy the buffer pointed to by result. I'm assuming C so I'm not casting to/from void* explicitly.

    void UserCallback( void* context, const char* result )
    {
        char** copied = context;
        *copied = malloc( strlen(result)+1 );
        strcpy( *copied, result );
    }
    
    void User()
    {
        char* result = NULL;
    
        Foo( UserCallback, &result );
    
        // Use result...
        if( result != NULL )
            printf("%s", result);
    
        free( result );
    }
    

    This is the most portable solution and handles even the toughest cases where the size of the returned string cannot be known in advance.

提交回复
热议问题