2017-06-27 166 views
-3

我有這樣的代碼:聲明未知大小的數組

//Class1.h - this is in a DLL solution 

class Sample 
{ 
    //members... 
} 

static Sample m_sample[1]; //size is not known - it will be given by the application that references the DLL 

//function to insert data on to array m_sample 
void AddSample(Sample** sample, members....) 
{ 
    static int index; 
    sample[index++] = new Sample(members...); 
} 

//in the cpp file in the EXE solution 

void InitSample() 
{ 
    AddSample(&m_sample, members....); 
} 

,這讓我這個錯誤:

error C2664: 'AddSample' : cannot convert parameter 1 from 'Sample (*)[1]' to 'Sample **' 

我明白陣列的聲明和函數聲明爲參數是不同的。 我不知道的是如果在DLL編譯時未知大小,如何聲明數組(如同靜態數組和參數) ??

注: 我已經嘗試使用std ::向量作爲容器,這讓我LNK錯誤(未定義的符號),並在谷歌看到,它是使用STL功能不好的設計(或至少這就是我記得)所以請不要建議使用矢量

我還在學習C++(MFC),指針的概念對我來說還不清楚。

謝謝!

編輯:強調已經嘗試過的載體

+2

數組是**不是**指針,而指針是**不是**數組。使用'std :: vector'。 – StoryTeller

+2

使用'static std :: vector m_sample;' –

+7

_「,並在Google上看到,使用STL函數是錯誤的設計」_tar和羽毛傳播這樣純粹的東西的人! –

回答

0

由於應用程序及其DLL可能有不同的堆,你要確保數據分配和動態緩存的版本中一直做的用法相同的模塊。

您的DLL保存主要的Samples緩衝區,所以它必須確定它的大小。如果你想要exe來控制,添加一個API函數並動態分配緩衝區從DLL,使用std :: vector聽起來像一個不錯的選擇。你可以在這種情況下提供一種釋放緩衝區的方法。

在你的dll文件中 - 當緩衝區爲空時返回採樣數意味着我們總是成功的,當然,如果緩衝區足夠大,當不爲空時。

請注意,該功能也可能阻塞,直到請求的採樣數量可用。這是您做出的設計決策。

int GetSamples(Sample* buffer, int maxSamples) 
{ 
    // if buffer is NULL, returns the number of available samples. 
    // if nuffer is not NULL, copies up to maxSamples in buffer 
    // else returns the number of samples copied 
    if (!buffer) 
    return nAvailableSamples; // < external, the number of samples in primary buffer. 

    int nSamples = min(maxSamples, nAvailableSamples); 

    // copy nSamples to buffer here, then remove them 
    // from your dll primary buffer 

    return nSamples; 
} 

在你的exe文件中。這只是一個例子,因爲我不知道你的應用的功能。

void SamplesGrabLoop() // a function in your app. 
{ 
    // .... 
    std::vector<Sample> buffer(64 << 10); // grab 64k samples max, actual value depends on your app. 

    while(1)        // as an example, use your own logic 
    { 
    int nSamples = GetSamples(&buffer[0], buffer.size()); 

    ConsumeSamples(&buffer[0], nSamples); // whatever your app does.. 

    // ... 
    // ... 
    // Sleep() or some mechanism to wait for samples to be available would be judicious here. 
    // otherwise, your app could use 100% of CPUs getting nothing most of the time. 
    } 
    // ... 
} 

我的有關使用矢量建議....始終使用指針來從應用數據傳遞到一個dll,從DLL到應用程序,或者從一個DLL到另一個DLL。可以在任何其他地方使用std :: vector和其他智能指針。不要直接調用new,當MFC文檔調用它時,不要直接調用CWnd派生的對象。如果您在dll中動態分配緩衝區或變量,請將其釋放到同一個dll中。 exe文件也一樣。

您可以安全地將句柄傳遞給exe和dll。這對事件,窗口和文件句柄很有用。你也可以安全地在dll中創建一個窗口句柄,並在exe中調用CloseHandle,反之亦然。

+0

*「您可以安全地傳遞手柄來回移動exe和dll,這對於窗口手柄非常有用。」* - 這是不正確的。 Windows是USER對象,由'HWND'引用。另一方面,「HANDLE」通常指內核對象。任何一種句柄類型都可以通過值傳遞,但是它們是不同的類型,具有不同的清理語義(例如,在HWND中不調用'CloseHandle')。 – IInspectable