Question

I am writing an Excel XLL addin using C++, where I want my function to return a string to Excel using the predefined XLOPER12.

As I understanded, Excel require the function to return a pointer that points to a memory,and then it makes a shallow copy then goes away without clearing the memory allocated in the function. So if I write something like:

extern "C" LPXLOPER12 WINAPI strgen() {
    XLOPER12 res;

    res.xltype = xltypeString;
    res.val.str = (XCHAR*)malloc(2*sizeof(XCHAR));
    res.val.str[0] = (XCHAR)1;
    res.val.str[1] = L"X";

    return (LPXLOPER12)&xRes;
}

But apparently this will cause a memory leak. Someone suggests that I could declare res as static variable, but i don't really know how to initialize it.

All suggestions are welcomed.

Best

Was it helpful?

Solution

Save yourself some trouble and use https://xll.codeplex.com. Complete code to register and define the function is

static AddIn12 xai_strgen(
    L"?strgen", L"STRGEN",
    XLL_LPOPER12, L"");
LPOPER12 WINAPI strgen() 
{
#pragma XLLEXPORT
    static XLOPER12 xRes(L"X");

    return &xRes;
}

OTHER TIPS

You can try to declare static array and return it's address

XCHAR s_res[3] = {0};
XLOPER12 res;
extern "C" LPXLOPER12 WINAPI strgen() {


res.xltype = xltypeString;
res.val.str = (XCHAR*)s_res;
res.val.str[0] = (XCHAR)1;
res.val.str[1] = L"X";

return (LPXLOPER12)&res;
}

Pay an attention that you shouldn't move s_res inside a function, because it will have a stack storage, that will be cleared when the function returns

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top