从C ++返回动态分配的内存为C [英] Return dynamically allocated memory from C++ to C

查看:108
本文介绍了从C ++返回动态分配的内存为C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DLL,它必须是从C等可用,所以我不能使用字符串对象等作为一个正常的可以,但我不知道如何做到这一点安全。

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 *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    return ss.str().c_str();
}

可以在C字符串来当SS脱落堆栈破坏?我假设如此...

could the c string be destroyed when ss falls off the stack? I'm assuming so...

另一个选择可能是在堆上创建一个新的字符串,但什么是要释放的?

Another option may be to create a new string on the heap, but what is going to deallocate that?

const char *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    char *out = new char[ss.str().size()];
    strcpy(ss.str().c_str(), out);
    return out;//is out ever deleted?
}

这同样适用于指向其他事情以及字符串

The same goes for pointers to other things as well as strings.

推荐答案

因为你返回一个指针到堆栈的对象,这将被摧毁的第一个变种不起作用。 (更多presisely,你的指针返回到堆内存,界河已经被删除了()。)更糟糕的是,它甚至可能会工作一段时间,如果没有人改写了内存,使得它非常难以调试。

The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug.

接下来,你不能,除非你返回一个指针静态字符串这样返回一个const char *

Next, you can not return a const char* unless you return a pointer to a static string like this:

const char *GetString()
{
    return "a static string in DATA segment - no need to delete";
}

您第二个变种已返回内存与新的()分配到一个C程序将调用free()的问题。那些可能不兼容。

You second variant has the problem of returning memory allocated with new() into a C program that will call free(). Those may not be compatible.

如果您返回一个字符串,C,有做2路:

If you return a string to C, there are 2 way to do that:

char *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    return strdup( ss.str().c_str() ); // allocated in C style with malloc()
}

void foo()
{
    char *p = GetString();
    printf("string: %s", p));
    free( p ); // must not forget to free(), must not use delete()
}

char *GetString(char *buffer, size_t len)
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    return strncpy(buffer, ss.str().c_str(), len); // caller allocates memory
}

void foo()
{
    char buffer[ 100 ];
    printf("string: %s", GetString(buffer, sizeof( buffer ))); // no memory leaks
}

根据你的内存处理政策。

depending on you memory handling policy.

作为一项规则,你永远不能返回一个指针或引用自动对象在C ++中。这是在许多C ++的书分析了常见的错误之一。

As a rule, you can NOT ever return a pointer or a reference to an automatic object in C++. This is one of common mistakes analyzed in many C++ books.

这篇关于从C ++返回动态分配的内存为C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆