1

I am currently working on a project where I have to build a shell for a C++ dll, so a new C# GUI can use its functions. However I got the following problem, in the C++ portion I have to create a new thread for specific reasons, and I want to pass an int array to the new thread. Note that the values assigned to the array in the function in which this happens are gained from the C# portion of the code.

__declspec( dllexport ) void CreateReportPane(int &id, int &what)
{
    DWORD threadId; 
    int iArray[2] = { id, what};    

    HANDLE hThread = CreateThread( NULL, 0, CreateReportPaneThread, iArray, 0,  &threadId);
    if (hThread == NULL) 
    {           
        ExitProcess(3);
    }    
}

The problem arises in the new thread, I can reliably fetch the first value out of the array, but the 2nd value seems to be released, here is the code on the other side.

DWORD WINAPI CreateReportPaneThread(LPVOID lparam)
{
    int id, what;
    id = *(( int * )lparam);
    what = *(((int *)lparam)+1) ; 
    CreateReportPaneOriginal(id, what);

    return 0;
}

Is there any way to prevent the values in the array from getting released while not holding the original thread captive? A big thank you in advance

4

2 回答 2

3
int iArray[2] = { id, what};    

HANDLE hThread = CreateThread(...,CreateReportPaneThread, iArray, ...);

问题是这iArray是一个本地数组,这意味着当函数CreateReportPane()返回时它会被破坏。所以CreateReportPaneThread()所指的是不存在的。你得到第一个值只是偶然。没有这样的保证,你甚至会得到第一个值。

使用动态数组:

int * iArray  = new int[2];
iArray[0] = id;
iArray[1] = what;

HANDLE hThread = CreateThread(...,CreateReportPaneThread, iArray, ...);

完成后请记住在以下位置编写解除分配数组CreateReportPaneThread

DWORD WINAPI CreateReportPaneThread(PVOID *data)
{
     int *array = static_cast<int*>(data);

     int id = array[0], what = array[1];

     delete []array; //MUST DO IT to avoid memory leak!

     //rest of your code
}
于 2012-11-08T09:07:26.040 回答
2

动态分配数组以防止数组在退出时超出范围CreateReportPane()

int* iArray = new int[2];
iArray[0] = id;
iArray[1] = what;    

否则线程正在访问一个不再有效的数组,这是未定义的行为。当不再需要它时,线程例程CreateReportPaneThread()必须然后数组(注意使用and not )。delete[]delete[]delete

于 2012-11-08T09:06:29.727 回答