[英]Return value from DLL function
我知道DLL通常具有自己的堆,將變量存儲在其中。我的DLL函數使用一個指向wchar_t變量的指針,並且每當我嘗試在其中輸入值時,它都會簡單地退出該函數,而將指針指向一個我假設的錯誤位置是因為堆被破壞了。
如果我的DLL函數提供了需要傳遞回的某種數據,那么有人可以舉一個例子說明如何將字符串格式的數據返回給原始主函數嗎?
使用Visual Studio 2010。
編輯:我可以提供一些示例代碼,但我沒有指出要點,因為我只是想就有關dll及其功能的內存處理方式進行示例/說明。 問我您需要什么信息,我會盡力提供。
好吧,讓您對應用程序的功能有所了解,它是一個COM服務器DLL。 接口是IProperty,對象稱為PropertyObject。 DLL是由我使用PropertyObject方法單獨構建的。 我正在研究的方法是Getproperty。
STDMETHODIMP PropertyObject::GetProperty(int arg1, wchar_t* arg2)
{
arg2 = L"Test";
cout << *arg2 << endl;
return S_OK;
}
int main()
{
CoInitialize(NULL);
IClassFactory * pClassFactory = NULL;
HRESULT hr;
hr = CoGetClassObject(
CLSID_PropertyObject,
CLSCTX_SERVER,
NULL,
IID_IClassFactory,
(void **) &pClassFactory);
if (SUCCEEDED(hr))
{
wchar_t x = NULL;
IProperty *pProperty = NULL;
hr = pClassFactory->CreateInstance(NULL, IID_IProperty, (void **) &pProperty);
hr = pProperty->GetProperty(2, &x);
cout << x << endl;
}
return 0;
}
如果您對所有參與程序均使用相同版本的Visual Studio編譯這一事實(這意味着它們都使用std :: string所包含的STL的相同版本)有100%的肯定,則可以使用std: :string類。
如果需要互操作,最好的選擇是傳入一個char *和一個length並寫入提供的緩沖區。 讓調用者處理內存。 那是C風格,也是您最安全的選擇。
原來我仍在考慮像普通字符數組一樣的wchar_t指針。 這是我的修改代碼:
STDMETHODIMP PropertyObject::GetProperty(int arg1, wchar_t* arg2)
{
wcscpy(arg2, L"Test"); // This is the function that i needed to be using.
return S_OK;
}
int main()
{
CoInitialize(NULL);
IClassFactory * pClassFactory = NULL;
HRESULT hr;
hr = CoGetClassObject(
CLSID_PropertyObject,
CLSCTX_SERVER,
NULL,
IID_IClassFactory,
(void **) &pClassFactory);
if (SUCCEEDED(hr))
{
wchar_t *x = new wchar_t; // Before, this was a normal variable. Changed it to a pointer.
IProperty *pProperty = NULL;
hr = pClassFactory->CreateInstance(NULL, IID_IProperty, (void **) &pProperty);
hr = pProperty->GetProperty(2, x); // Passed the pointer instead of an address to a normal variable.
wcout << x << endl; // wcout instead of cout. It worked.
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.