Ken Yup
Ken Yup

Reputation: 23

How to return integer & char * variable in C++ native dll in a sametime?

I tried to build a dll which could return the int and char * in Visual Studio in Windows, however it occurred the memory leaks, I builded this dll for other language, of course, in today's PCs, the memory is very large that I could ignore this bug completely, however I thought I would try my best to my everything. How to resolve this issue? I'm not familiar with C++, I have seen many web pages to check how to build a dll. I wish I could return multiple char * in the future when this problem has been resolved, any suggestions?

int   __stdcall  postsbinv(char ** retstring)
{
    std::wstring wstrinvnum = L"1215265152";
    size_t outputSize = wstrinvnum.length() + 1; // +1 for null terminator
    char * retinvnumtemp = new char[outputSize];//memory leaks
    size_t charsConverted = 0;
    const wchar_t * wchar_invnum = wstrinvnum.c_str();
    wcstombs_s(&charsConverted, retinvnumtemp, outputSize, wchar_invnum, wstrinvnum.length());//convert the utf-16 to ascii
    *retstring = retinvnumtemp;//point to the char *
    return 0;
}

PS: for using by other language, I have use the char *

Upvotes: 2

Views: 86

Answers (2)

kfsone
kfsone

Reputation: 24249

If you are allocating memory with new you need to release it with delete and that's going to be a problem if the caller is in another language.

So you will need to provide a second function to release the memory.

int __stdcall postsbinv(char** retstring)
{
    *retstring = new char[outputSize];
}

void __stdcall free_sbinv(char** retstring)
{
    if (*retstring)
        delete[] *retstring;
}

Upvotes: 3

Sachin Godara
Sachin Godara

Reputation: 502

You can do something like this to improve your code:

char *retinvnumtemp = new char[outputSize];

if(retinvnumtemp==NULL) {
    // enter code here
} else {
    // enter code here
}

And also to prevent from memory leaks you should use

delete [] retinvnumtemp;

Upvotes: 0

Related Questions